语义相同的两个属性的 TypeId 应该不同还是相同?

发布于 2024-12-24 23:18:09 字数 1063 浏览 3 评论 0原文

MSDN 状态属性 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
        }

Or

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终止放荡 2024-12-31 23:18:09

TypeId 属性用于区分同一成员上相同属性的实例。这意味着,仅当属性用声明 AllowMultiple=trueAttributeUsageAttribute 修饰时才需要实现它。

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

您可以在此 MSDN 链接 的注释中找到有关该属性的提示对于 GetAttributes 方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文