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

问题描述 投票:0回答:3

坦白一点,我从来没有写过属性类。我知道它们的目的可能是用标志或额外功能装饰类。

有人能给我一个简单的例子,不仅可以创建属性并将其应用于类,还可以利用另一个代码块中的属性。我见过的唯一使用任何形式的属性的代码示例是通过反射来实现的,尽管我一直希望有一种无需反射即可使用它们的方法。

c# attributes custom-attributes class-attributes
3个回答
12
投票

属性总是与反射一起使用。它们在编译时被嵌入到类型的元数据中,读取它们的唯一方法是通过反射。当您想要编写一个类型并且想要将一些元数据与其相关联时可以使用属性,这些元数据可以被这种类型的消费者使用。


6
投票

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

有关属性和特性之间差异的讨论,请参见链接


5
投票

首先创建你的属性

public class ImportableAttribute : Attribute
{

}

然后是一个包含使用属性的项目的类

[ImportableAttribute]
public class ImportClass
{
    [ImportableAttribute]
    public string Item {get; set;}
}

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

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

if (property.IsDefined(typeof(ImportableAttribute),true))
{
     // do something
}

上课:

typeof(ImportClass).IsDefined(typeof(ImportableAttribute), true);
© www.soinside.com 2019 - 2024. All rights reserved.