【问题标题】:Should the TypeIds of two attributes which are semantically identical be different or the same?两个语义相同的属性的 TypeId 应该不同还是相同?
【发布时间】:2012-01-13 16:26:09
【问题描述】:

MSDN states 的属性TypeId 表示:

在实现时,此标识符只是属性的类型。但是,唯一标识符旨在用于标识相同类型的两个属性。

然而,预期用途是区分单个属性实例(例如,与应用它们的类的不同实例相关联的那些实例)还是区分具有相同类型但由于其属性值在语义上不同的属性?

例如,假设我有以下内容:

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

【问题讨论】:

    标签: c# .net reflection typeid


    【解决方案1】:

    TypeId 属性用于区分同一成员上同一属性的实例。意思是,只有在属性被声明为AllowMultiple=trueAttributeUsageAttribute 修饰时才需要实现它。

    例如,如果您要使用多个 AmpVolume 属性装饰一个类或方法,则 TypeId 将区分这些实例。

    您可以在MSDN link for GetAttributes 方法的注释中找到有关该属性的提示。

    【讨论】:

    • 我明白了,我误解了TypeId在什么范围内操作;它的用法现在很清楚了,谢谢!
    猜你喜欢
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多