Should the TypeIds of two attributes which are semantically identical be different or the same?

StackOverflow https://stackoverflow.com/questions/8728793

  •  14-04-2021
  •  | 
  •  

Domanda

MSDN states of the property TypeId that:

As implemented, this identifier is merely the Type of the attribute. However, it is intended that the unique identifier be used to identify two attributes of the same type.

Is the intended use however, to distinguish between individual attribute instances (e.g. those associated with different instances of the class to which they are applied) or between attributes which have the same type but due to their property values are semantically different?

For example, say I had the following:

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
{
}

Should I implement TypeId as

        get
        {
            return (object)this; //TypeId identifies every individual instance of the attribute
        }

Or

        get
        {
            return (object)MaxVolume; //If we compare two AmpVolume attributes, they should be the same if the volume is the same, right?
        }
È stato utile?

Soluzione

The TypeId property is used to distinguish between instances of the same attribute on the same member. Meaning, it's required to implement it only when the attribute is decorated with AttributeUsageAttribute which declares AllowMultiple=true.

For example, if you'd decorate a class or method with multiple AmpVolume attributes, then the TypeId will distinguish between those instances.

You can find a hint on the property in the note at this MSDN link for GetAttributes method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top