两个属性在语义上相同的TypeIds应该是不同的还是相同的?
属性TypeId
MSDN状态 :
实现时,该标识符仅是属性的类型。 但是,意图是使用唯一标识符来标识相同类型的两个属性。
但是,预期用途是区分单个属性实例(例如,与应用它们的类的不同实例相关联的那些实例),还是属于具有相同类型但由于其属性值的属性在语义上不同?
例如,假设我有以下内容:
public sealed class AmpVolume : System.Attribute { public int MaxVolume { get; set; } public AmpVolume(int maxvolume) { MaxVolume = maxvolume; } } [AmpVolume(11)] public class SpinalTapGuitarAmp { } [AmpVolume(11)] public class SpinalTapBassAmp { } [AmpVolume(10)] public class RegularAmp { }
我应该将TypeId实现为
get { return (object)this; //TypeId identifies every individual instance of the attribute }
要么
get { return (object)MaxVolume; //If we compare two AmpVolume attributes, they should be the same if the volume is the same, right? }
TypeId属性用于区分同一成员上相同属性的实例。 意思是,只有在使用声明AllowMultiple=true
AttributeUsageAttribute
修饰AttributeUsageAttribute
时才需要实现它。
例如,如果您使用多个AmpVolume属性修饰类或方法,则TypeId将区分这些实例。
您可以在此MSDN链接的注释中找到有关GetAttributes
方法的提示。