[英]C# Reflection with enum array
我有一個帶有自定義枚舉的類:
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);
那可能嗎?
以下應該做您想要的。
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);
這應該工作:
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);
如果要枚舉枚舉的所有可能值並作為數組返回,請嘗試使用以下幫助器函數:
public class EnumHelper {
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
然后,您可以簡單地調用:
Capabilities[] array = EnumHelper.GetValues<Capabilities>();
如果那不是您想要的,那我就不確定您的意思了。
你可以試試這個
foreach (PropertyInfo property in prs)
{
string[] enumValues = Enum.GetNames(property.PropertyType);
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.