2012-02-09 35 views
0

說中String類型的屬性屬性我有屬性:看看是否被應用到是類屬性

public class Column_Attribute : Attribute 
{ 
    public string DbType { get; set; } 
    public bool IsPrimaryKey { get; set; } 
} 

那麼我可以說屬性應用到的屬性爲:

[Column_Attribute(DbType = "Integer", IsPrimaryKey = true)] 
public int Id { get; set; } 

現在我怎樣才能從屬性類中獲得有關屬性Id的信息。換句話說,我想要做的事,如:

public class Column_Attribute : Attribute 
{ 
    // constructor 
    public Column_Attribute(){ 
     // if the property has the name Id do something... 
     // OR 
     // if this is an attribute of a property do something 
     // if this is an attribute of a field do something else 

     // If this attribute is targeting a property that is a string do something 
    } 

    public string DbType { get; set; } 
    public bool IsPrimaryKey { get; set; } 
} 

其實我需要知道,如果被應用到這是一個字符串的屬性的屬性。

我知道如何做到這一點與反射,但我想在屬性類內做到這一點。那可能嗎。希望我正確地解釋我自己

回答

1

如果沒有反射,你不能這樣做,因爲在調用GetCustomAttributes()(這是反射的一部分)之前,構造函數中的代碼將不會被執行。

看到http://msdn.microsoft.com/en-us/library/z919e8tw(v=vs.80).aspx

調用GetCustomAttributes上SampleClass導致作者對象 構造和初始化上述

如果你希望你的屬性類包含的加工代碼,你可以創建一個方法接收屬性名稱。在調用GetCustomAttributes()時,屬性名稱將可用。