使用自定义属性最简单最优雅的方法是什么

Jim*_*ffa 3 c# attributes custom-attributes class-attributes

所以有点忏悔,我从来没有写过属性类.我知道他们的目的是用标志或额外的功能来装饰类.

有人可以给我一个简单的例子,不仅可以创建属性并将其应用于类,而且可以使用另一个代码块中的属性.我见过的唯一使用任何形式属性的代码示例都是通过反射来实现的,尽管我一直希望有一种方法可以在没有反射的情况下使用它们.

Dar*_*rov 8

属性始终与反射一起使用.它们在编译期间被烘焙到类型的元数据中,并且读取它们的唯一方法是通过反射.当您想要编写类型并且想要将某些元数据与此类型的消费者使用时,可以使用属性.

  • 实际上有一些属性可以控制编译器的行为.例如,[Conditional]属性可能完全隐藏方法. (2认同)

Eri*_*ert 6

使用另一个代码块中的属性的最简单和最优雅的方法是使用属性而不是属性.

有关 属性和属性之间差异的讨论,请参见http://blogs.msdn.com/b/ericlippert/archive/2009/02/02/properties-vs-attributes.aspx.


And*_*eas 5

首先创建你的属性

public class ImportableAttribute : Attribute
{

}
Run Code Online (Sandbox Code Playgroud)

然后是一个带有使用该属性的项目的类

[ImportableAttribute]
public class ImportClass
{
    [ImportableAttribute]
    public string Item {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

然后检查该属性是否使用该属性。可以通过课程来完成..当然:)

PropertyInfo property = typeof(ImportClass).GetProperty("Item");

if (property.IsDefined(typeof(ImportableAttribute),true))
{
     // do something
}
Run Code Online (Sandbox Code Playgroud)

有一个类:

typeof(ImportClass).IsDefined(typeof(ImportableAttribute), true);
Run Code Online (Sandbox Code Playgroud)