get type IRepo<T> when i have the string name for T
basically
I have
string s = "Foo"
I need to o开发者_运维百科btain
Type t = IRepo<Foo>
but from string
Something like this, using Type.MakeGenericType
:
Type arg = Type.GetType(s);
Type definition = typeof(IRepo<>);
Type concrete = definition.MakeGenericType(arg);
Note that Type.GetType(string)
comes with a few caveats:
- You need to specify the type's full name, including namespace
- If you want to get a type from an assembly other than
mscorlib
or the calling assembly, you have to include the assembly name - If you're including the assembly name and it's strongly typed, you need the full assembly name including version etc.
Type t = typeof (IRepo<>).MakeGenericType(Type.GetType(s));
You can do the following:
var someTypeName = "Foo";
var someType = Type.GetType("Namespace.To." + someTypeName);
typeof(IRepo<>).MakeGenericType(someType);
You first need to get the Type
of Foo
, and then you can pass that into Type.MakeGenericType.
精彩评论