I'm trying to create an instance of a generic class using a Type object.
Basically, I'll have a collection of objects of varying types at runtime, and since there's no way for sure to know what types they exactly will be, I'm thinking that I'll have to use Reflection.
I was working on something like:
Type elType = Type.GetType(obj);
Type genType = typeof(GenericType<>).MakeGenericType(elType);
object obj = Activator.CreateInstance(genType);
Which is well and good. ^___^
The problem is, I'd like to access a method of my GenericType<> instance, which I can't because it's typed as an object class. I can't find a way to cast it obj into the specific GenericType<>, because that was the problem in the first place (i.e., I just can't put in something like:)
((GenericType<elType>)obj).MyMethod();
How should one go about tackling this problem?
Many thanks! ^___^
You would have to continue using Reflection to invoke the actual method:
// Your code
Type elType = Type.GetType(obj);
Type genType = typeof(GenericType<>).MakeGenericType(elType);
object obj = Activator.CreateInstance(genType);
// To execute the method
MethodInfo method = genType.GetMethod("MyMethod",
BindingFlags.Instance | BindingFlags.Public);
method.Invoke(obj, null);
For more information see Type.GetMethod and MethodBase.Invoke.
Once you start the reflection game you have to play it till the end. The type is not known at compile time, so you cannot cast it. You'll have to invoke the method by reflection:
obj.GetType().InvokeMember(
"MyMethod",
BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
null,
obj,
null
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With