2013-01-09 157 views
2

C#反思我有自定義枚舉類:與枚舉陣列

public enum Capabilities{ 
PowerSave= 1, 
PnP =2, 
Shared=3, } 

我班

public class Device 
{ 
     .... 
    public Capabilities[] DeviceCapabilities 
    { 
    get { // logic goes here} 
    } 

是否有使用反射來得到這個領域的運行期間的值的方法嗎? 我嘗試以下,但得到空引用異常

PropertyInfo[] prs = srcObj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); 
foreach (PropertyInfo property in prs) 
{ 
    if (property.PropertyType.IsArray) 
    { 
     Array a = (Array)property.GetValue(srcObj, null); 
    }  
} 

編輯:謝謝您的回答,我真正需要的是一種動態獲取值,而不需要指定枚舉類型。 類似於:

string enumType = "enumtype" 
var property = typeof(Device).GetProperty(enumType); 

這可能嗎?

+0

你是什麼意思'獲得這個領域的價值'?簡單地閱讀該數組,然後按照你的意願做 –

+1

這裏適合使用'[Flags]'的聲音:http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx –

+0

你有堆棧嗎?跟蹤來驗證NullReferenceException來自哪裏?它看起來可能來自您的DeviceCapabilities屬性中的邏輯,或來自對象中的另一個屬性。 –

回答

0

這應該工作:

var source = new Device(); 

    var property = source.GetType().GetProperty("DeviceCapabilities"); 
    var caps = (Array)property.GetValue(source, null); 

    foreach (var cap in caps) 
     Console.WriteLine(cap); 
1

以下應該做你的願望。

var property = typeof(Device).GetProperty("DeviceCapabilities"); 

var deviceCapabilities = (Capabilities[])property.GetValue(device); 

請注意,方法Object PropertyInfo.GetValue(Object)是.NET 4.5中的新增功能。在以前的版本中,您必須爲索引添加額外的參數。

var deviceCapabilities = (Capabilities[])property.GetValue(device, null); 
0

如果要列舉一個枚舉的所有可能的值,並返回一個數組,然後嘗試這個輔助功能:

public class EnumHelper { 
    public static IEnumerable<T> GetValues<T>() 
    { 
     return Enum.GetValues(typeof(T)).Cast<T>(); 
    } 
} 

然後,您只需撥打:

Capabilities[] array = EnumHelper.GetValues<Capabilities>(); 

如果那不是你以後的話,我不確定你的意思。

0

你可以試試這個

foreach (PropertyInfo property in prs) 
{ 
    string[] enumValues = Enum.GetNames(property.PropertyType); 
} 

希望它能幫助。