簡體   English   中英

使用自定義屬性最簡單最優雅的方法是什么

[英]What's the simplest most elegant way to utilize a custom attribute

所以有點懺悔,我從來沒有寫過屬性類。 我知道他們的目的是用標志或額外的功能來裝飾類。

有人可以給我一個簡單的例子,不僅可以創建屬性並將其應用於類,而且可以使用另一個代碼塊中的屬性。 我見過的唯一使用任何形式屬性的代碼示例都是通過反射來實現的,盡管我一直希望有一種方法可以在沒有反射的情況下使用它們。

屬性始終與反射一起使用。 它們在編譯期間被烘焙到類型的元數據中,讀取它們的唯一方法是通過反射。 當您想要編寫類型並且想要將某些元數據與此類型的消費者使用時,可以使用屬性。

使用另一個代碼塊中的屬性的最簡單和最優雅的方法是使用屬性而不是屬性

有關屬性和屬性之間差異的討論,請參見http://blogs.msdn.com/b/ericlippert/archive/2009/02/02/properties-vs-attributes.aspx

首先創建您的屬性

public class ImportableAttribute : Attribute
{

}

然后是一個包含使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM