【问题标题】:Why is the attribute called [Serializable] and not [SerializableAttribute] (C#) [duplicate]为什么属性称为 [Serializable] 而不是 [SerializableAttribute] (C#) [重复]
【发布时间】:2015-06-27 13:24:25
【问题描述】:

我对 .NET 属性的理解存在漏洞。 Serializable 类的类定义是这样的:

namespace System {
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)]
    [ComVisible(true)]
    public sealed class SerializableAttribute : Attribute {
        public SerializableAttribute();
    }
}

为什么当你使用它时它被称为 [Serializable] 而不是 [SerializableAttribute]?尽管您似乎可以使用后者。

这里是否存在某种别名?这将是一个“doh!”我怀疑的那一刻......

【问题讨论】:

  • 谢谢 - 这是一个重复的问题。我搜索了属性别名而不是缩写。通常一半的问题是在你不知道答案时知道要搜索什么

标签: c# .net custom-attributes


【解决方案1】:

C# 语言规范允许编译器推断类型名称的“属性”部分。正如@Jim 在评论中解释的那样,您可以明确包含类型名称的“属性”部分,但这不是必需的。这两种用法在语义上是等效的。

MSDN 文章 here 在“使用属性类”部分下进行了更详细的介绍。最后但同样重要的是,C# 语言规范中允许这种行为的部分的实际 citation

按照惯例,属性类以Attribute后缀命名。属性的使用可以包括或省略这个后缀。

【讨论】:

  • 是的,正确的。如果你喜欢,你仍然可以添加“属性”,但它被认为是多余的,因此有别名。
猜你喜欢
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 2020-04-25
  • 2016-06-22
  • 2011-07-23
  • 2016-11-15
  • 2012-11-03
  • 2021-08-02
相关资源
最近更新 更多