C# 像[Description]这样的属性有什么典型用法?

C# 像[Description]这样的属性有什么典型用法?,c#,attributes,C#,Attributes,我看到一些代码片段如下: [Description("This method is used to do something.")] static void SomeMethod() { } 我想知道我们想要的是否只是描述方法的含义,为什么不使用以下注释: /// <summary> /// This method is used to do something. /// </summary> static void SomeMethod() { } // ///这个

我看到一些代码片段如下:

[Description("This method is used to do something.")]
static void SomeMethod()
{
}
我想知道我们想要的是否只是描述方法的含义,为什么不使用以下注释:

/// <summary>
/// This method is used to do something.
/// </summary>
static void SomeMethod()
{
}
//
///这个方法是用来做某事的。
/// 
静态方法()
{
}
实际上,IntelliSense可以利用注释样式。那么,我们为什么要费心使用属性呢

更新
因此,虽然不是很准确,但我将属性作为comment的运行时版本。虽然注释仅适用于编辑时间

但在运行时可以访问
[Description]
等属性,而注释则不能。例如,演示如何从枚举中获取描述(其他答案演示如何从描述中解析枚举)。例如,这样的枚举可能看起来像:

public enum Fruit
{
    [Description("Apples are red or green, and tasty")]
    Apple,
    [Description("Pineapples are yellow inside, and acidic")]
    Pineapple,
}
下面是您的方法描述的外观:

var desc = typeof(ThatClass)
   .GetMethod("SomeMethod", BindingFlags.Static | BindingFlags.NonPublic)
   .GetCustomAttributes(typeof(DescriptionAttribute))
   .Cast<DescriptionAttribute>().ToList();
Console.WriteLine(desc[0].Description);
// prints "This method is used to do something."
var desc=typeof(该类)
.GetMethod(“SomeMethod”,BindingFlags.Static | BindingFlags.NonPublic)
.GetCustomAttributes(typeof(DescriptionAttribute))
.Cast().ToList();
Console.WriteLine(desc[0].Description);
//打印“此方法用于执行某些操作。”

我不认为在一种方法上使用它有什么意义,除非在一些不寻常的情况下,但是它有它的用途,并且与注释截然不同。

如果您正在实现一个用户控件,并且希望您的属性在
属性窗口中显示额外的描述,那么它也是一种很好的机制,可以提供有关属性的支持信息。您可以将此属性与
CategoryAttribute
组合,以便在
Properties窗口中将属性分组到类别中


我使用它作为一种方法,通过反射将enum映射到用户友好的文本。请看,是的,我认为最重要的一点是,即使在编译之后,它也可以通过编程访问,而“注释样式”被视为注释,因此在编译的项目上看不到。它为属性窗口提供了电源,选择属性或事件时,将在窗口底部看到描述文本。当然不是一个方法,不知道为什么要使用它。所以这实际上是另一个属性提供运行时信息而注释不能的例子。这是Visual Studio中内置功能的例子。如果希望属性为使用控件的用户提供额外信息,请为属性提供
DescriptionAttribute
属性。属性在运行时可用这一事实适用于所有属性,您可以使用反射获取这些属性,以便以后对类型及其成员进行操作。