2016-09-21 38 views
0

我有一个问题,通过强制通用列表。我获得了一个通用列表的值,并希望将其用作SomeMehtod的参数。创建列表<T>通过类型

List<MyClass> GenericList; 
var propList= this.GetType().GetProperty("GenericList").GetValue(this); 

SomeMethode(propList) <-- Does not work 
private void SomeMethode(List<T> genericList) 
{ 
} 

有人可以给我一个提示吗?我曾经试过,但它不会工作:

List<typeof(MyClass)> newPropList = propList; 

我的问题是,MyClass存储在类型变量:

var typesWithMyAttribute = 
    from a in AppDomain.CurrentDomain.GetAssemblies() 
    from t in a.GetTypes() 
    let attributes = t.GetCustomAttributes(typeof(XMLDataAttribute), true) 
    where attributes != null && attributes.Length > 0 
    select new { Type = t, Attributes = attributes.Cast<XMLDataAttribute>() }; 

foreach (var a in typesWithMyAttribute) 
{ 
    var propList = this.GetType().GetProperty(a.Type.Name + "List").GetValue(this); 
    SomeMethode<a.Type>(propList); <-- Won't work 
} 
+4

你能给出[MCVE]很难说出你想要达到的目标以及你得到的错误。 (“不起作用”并不像实际的错误信息那样有用。) –

+0

'propList'是一个'object',你应该先施放它。 –

+0

你应该把它作为'IList'而不是'List '来传递。你不知道'T'。但你知道它应该是一个'List <>' –

回答

2

您需要使用反射才能获得MethodInfo对于构造的方法SomeMethod

MethodInfo genericMethod = this.GetType().GetMethod("SomeMethode", BindingFlags.NonPublic); 
foreach (var a in typesWithMyAttribute) 
{ 
    MethodInfo constructedMethod = genericMethod.MakeGenericMethod(a.Type); 
    var propList = this.GetType().GetProperty(a.Type.Name + "List").GetValue(this); 
    constructedMethod.Invoke(this, new[]{propList}); 
} 

对于GetMethod您可能需要指定更多BindingFlags如果您SomeMethodestatic和/或private

MakeGenericMethod创建一个MethodInfo将类型参数appyling到泛型MethodInfo

然后你Invoke该方法通过你的propList作为参数。


请注意,您必须声明SomeMethode作为通用的,太:

private void SomeMethode<T>(List<T> genericList) 
{ 
} 
+0

谢谢René。这是工作 – Alex

0

您的方法必须是通用的,也是如此。

private void SomeMethode<T>(List<T> genericList) 
{ 
} 

这就是我现在可以帮助你,因为我不知道你想达到什么目的。

+0

关心我有同样的答案-1:p – pix