2013-06-04 48 views
0

我似乎無法能夠使用下面的代碼讀取自定義枚舉屬性:的MemberInfo屬性

public class CustomAttribute : Attribute 
{ 
    public CultureAttribute (string value) 
{ 
    Value = value; 
} 

public string Value { get; private set; } 
} 

public enum EnumType 
{ 
    [Custom("value1")] 
    Value1, 
    [Custom("value2")] 
    Value2, 
    [Custom("value3")] 
    Value3 
} 
... 
var memInfo = typeof(CustomAttribute).GetMember(EnumType.Value1.ToString()); 
// memInfo is always empty 
var attributes = memInfo[0].GetCustomAttributes(typeof(CustomAttribute), false); 

不知道如果我只是缺少明顯的東西在這裏或有在Mono/MonoMac中讀取自定義屬性的問題。

回答

1

你應該打電話GetMember()在給定的成員的類型當然:)在這種情況下,這是EnumType而不是CustomAttribute。 也修復了我認爲是屬性構造函數的複製粘貼錯誤。

完整的工作測試代碼(你應該知道與我們寧願這些給我們來完成自己半製作的電視節目23K名代表;)):

using System; 

public class CustomAttribute : Attribute 
{ 
    public CustomAttribute (string value) 
    { 
     Value = value; 
    } 

    public string Value { get; private set; } 
} 

public enum EnumType 
{ 
    [Custom("value1")] 
    Value1, 
    [Custom("value2")] 
    Value2, 
    [Custom("value3")] 
    Value3 
} 

class MainClass 
{ 
    static void Main(string[] args) 
    { 
     var memInfo = typeof(EnumType).GetMember(EnumType.Value1.ToString()); 
     Console.WriteLine("memInfo length is {0}", memInfo.Length); 
     var attributes = memInfo[0].GetCustomAttributes(typeof(CustomAttribute), false); 
     Console.WriteLine("attributes length is {0}", attributes.Length); 
    } 
} 

in operation

+0

哈哈我昨晚肯定工作得太晚了 - 今天早上又看了一遍,用一雙新的眼睛看過它,無論如何也會標記出來,因爲別人有類似的問題。 – James