我需要在某些属性类中添加Guid属性,就像这样:
public class SomeAttribute : Attribute {
private Guid foreignIdentificator;
public Guid ForeignIdentificator {
get { return this.foreignIdentificator; }
set { this.foreignIdentificator = value; }
}
}
但在属性定义中,我只能使用常量这些原始类型(我理解为什么,这让我感到合理)。解决方法可以是将 "ForeignIdentificator" 定义为字符串,并在运行时创建 GUID:
public class SomeAttribute : Attribute {
private string foreignIdentificator;
public string ForeignIdentificator {
get { return this.foreignIdentificator; }
set { this.foreignIdentificator = value; }
}
public Guid ForeignIdentificatorGuid {
get { return new Guid( ForeignIdentificator ); }
}
}
很不幸,我失去了类型安全性的检查。"ForeignIdentificator"属性可以包含任何字符串值,在创建Guid时会在运行时而不是编译时抛出异常。
我知道编译器会检查"System.Runtime.InteropServices.GuidAttribute"的字符串值以进行"Guid兼容性"检查。这个检查正是我需要的,但我不知道这个检查是否是硬编码在编译器中的,还是可以显式地定义(以及如何定义)。
您知道保护属性的"Guid兼容性"检查的方法吗?或者其他方法,如何实现类型安全的Guid定义? 谢谢。