Reputation: 9915
I have generic method of an object that I want to invoke. But I have no clue of T in that moment, all I know is type of T which is set to a property of the object.
public calass SomeClass{
public Type SomeType { get; set; }
public void SomeMethod<T>(){
}
}
...
var instance = new SomeClass();
...
Is it possible to do something like this?
instance.SomeMethod<SomeType>();
Upvotes: 0
Views: 62
Reputation: 393
You can add the following check in SomeMethod<T>:
if (!SomeType.IsAssignableFrom(typeof(T))) throw new Exception("Expecting type stored in SomeType.");
Or I would change the class to templated:
public class SomeClass<T>
{
public Type InstanceType { get { return typeof(T); } }
public void SomeMethod<T> () { }
}
Upvotes: 0
Reputation: 101701
Yes, you can call it using Reflection:
var method = instance.GetType().GetMethod("SomeMethod")
.MakeGenericMethod(instance.SomeType);
method.Invoke(instance);
Also note that SomeType
is the name of your property, not the type of your property.You need to specify the type when you want to call a generic method.
Upvotes: 2