Reputation: 1828
I want to instantiate a class via reflection as follows:
public class TestConsume<T> : BaseExecutor<T>
{
public overide SomeMethod(T input)
{
}
}
Where the BaseClass is:
public abstract class BaseExecutor<T> : IExecutor<T>
{
public T Execute(T input)
{
}
}
And the interface is:
public interface IExecutor<T>
{
void Execute(T input);
}
I've tried numerous ways to get the type of 'TestConsume' but it pretty much always return null. Any idea how to go about doing this?
the main way I've tried to get the type is:
Type type = Assembly.GetExecutingAssembly().GetType("Test.TestConsume");
I've also used Type.GetType() etc and I'm completely lost.
Upvotes: 0
Views: 97
Reputation: 1503290
To get Assembly.GetType
to work, you need to use the CLR name, which includes the generic arity - the number of type parameters it has:
Type type = Assembly.GetExecutingAssembly().GetType("Test.TestConsume`1");
That's assuming you need to do it using a string representation at all. If not, you can just use:
Type type = typeof(Test.TestConsume<>);
You'll then need to create the appropriate constructed type using Type.MakeGenericType
:
Type constructed = type.MakeGenericType(typeof(string)); // Or whatever
Upvotes: 2