[英]reflection to invoke methods of unknown property types
我想為我的視圖模型類的每個屬性IEnumerable<class>
調用通用方法'get_',以避免創建冗長的switch語句來顯式地獲取每個列表...有人知道如何獲取對象類型和一般的方法?
foreach (var prop in vm.GetType().GetProperties().Where(x => x.GetCustomAttributes<ExportAttribute>().Any()))
{
var objType = ??;
var method = objType.GetMethod(<by name>);
var list = method.Invoke(prop, null);
foreach (var item in list)
{
//do something
}
}
我會用類似的東西:
foreach (var prop in vm.GetType()
.GetProperties()
.Where(x => x.GetCustomAttributes<ExportAttribute>().Any()))
{
var list = (IEnumerable) prop.GetValue(vm, null);
foreach (var item in list)
{
// do something
}
}
現在, item
將被鍵入為object
……但是您實際上不能做得更好。 您的“執行操作”代碼無論如何都不能使用元素類型的任何成員,因為它可以是任何類型。
另一方面,如果您知道每個屬性都是實現IEnumerable<T>
,其中T
在每種情況下都具有相同的基本類型,那么由於.NET 4中引入的IEnumerable<T>
的通用協方差,您可以可以寫:
foreach (var prop in vm.GetType()
.GetProperties()
.Where(x => x.GetCustomAttributes<ExportAttribute>().Any()))
{
var list = (IEnumerable<BaseType>) prop.GetValue(vm, null);
foreach (var item in list)
{
// do something
}
}
然后,您可以訪問item.PropertyDeclaredInBaseType
。
請注意,我已將調用的目標更改為vm
而不是null
,因為您大概想要這些實例屬性...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.