2013-12-09 123 views
0

在所有關於自定義屬性的教程中,他們告訴我們如何創建和定義自定義屬性,這些屬性只不過是關於類/方法的簡單評論。 我想弄清楚如何從.NET中的這些自定義屬性中讀取某些方法。 例如:從.NET中讀取屬性

[SomeCustomAttr(param1, param2)] 
public void Method1() 
{ 
    read param1 from here 
    read param2 from here 
} 

有真正偉大的框架存在,這也與輸入的數據。有沒有人可以給我一些方向如何處理這個問題?

+0

請注意'param1'和'param2'只是'SomeCustomAttr'構造函數的參數。假設您的ctor將這些值分配給屬性,您只需按照該問題的信息,並在獲取屬性對象後訪問這兩個屬性。 –

回答

4

假設你指的是參數是自定義的屬性屬性類:

class Program 
{ 
    static void Main(string[] args) { 
     Test(); 
     Console.Read(); 
    } 

    [Custom(Foo = "yup", Bar = 42)] 
    static void Test() { 
     // Get the MethodBase for this method 
     var thismethod = MethodBase.GetCurrentMethod(); 

     // Get all of the attributes that derive from CustomAttribute 
     var attrs = thismethod.GetCustomAttributes(typeof(CustomAttribute), true); 

     // Assume that there is just one of these attributes 
     var attr1 = (CustomAttribute)attrs.Single(); 

     // Print the two properties of the attribute 
     Console.WriteLine("Foo = {0}, Bar = {1}", attr1.Foo, attr1.Bar); 
    } 
} 

class CustomAttribute : Attribute 
{ 
    public string Foo { get; set; } 
    public int Bar { get; set; } 
} 

注意,屬性是有點特殊的,因爲他們可以採取命名參數(對應於公共屬性名稱),沒有聲明任何構造函數。

0

反射是獲取屬性的正確方法。

  var TypeObj = typeof(Type1); 
      var MethodInfoObj = TypeObj.GetMethod("Method1"); 

      // var AllAttributes= MethodInfoObj.GetCustomAttributes(true); 

      var Attributes = MethodInfoObj.GetCustomAttributes(typeof(SomeCustomAttr), true); 
      if (Attributes.Length > 0) 
      { 
       var AttributeObj = Attributes[0] as SomeCustomAttr; 
       var value_param1 = AttributeObj.param1 ; 
      } 
+1

一些建議:1)不要使用'UpperCamelCase'作爲變量名(例如'TypeObj') - C#約定將它用於類名。 2)如果你使用'as',你應該檢查'null'。 3)我確信這是某個地方的一個片段,但如果你正確地縮進它,它會很好,以便於閱讀。 –