Reputation: 97
I have a problem by casting a generic list. I get the value of a generic list and want to use it as a parameter for the SomeMehtod
.
List<MyClass> GenericList;
var propList= this.GetType().GetProperty("GenericList").GetValue(this);
SomeMethode(propList) <-- Does not work
private void SomeMethode(List<T> genericList)
{
}
Can anybody give me a hint? I have tried this but it won't work:
List<typeof(MyClass)> newPropList = propList;
My Problem is that MyClass
is stored in type variable:
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
}
Upvotes: 0
Views: 137
Reputation: 43936
You need to use reflection to get a MethodInfo
for the constructed method 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});
}
For GetMethod
you may need to specify more BindingFlags
if your SomeMethode
is static
and/or private
.
MakeGenericMethod
creates a MethodInfo
appyling the type arguments to the generic MethodInfo
.
Then you Invoke
that method passing your propList
as argument.
Note that you have to declare SomeMethode
as generic, too:
private void SomeMethode<T>(List<T> genericList)
{
}
Upvotes: 2
Reputation: 2950
Your method must be generic, as well.
private void SomeMethode<T>(List<T> genericList)
{
}
That's all I can help you with at the moment, since I have no idea what you're trying to achieve.
Upvotes: 0