开发者

get type IRepo<T> when i have the string name for T

开发者 https://www.devze.com 2023-01-11 02:17 出处:网络
basically I have string s = \"Foo\" I need to o开发者_运维百科btain Type t = IRepo<Foo> but from stringSomething like this, using Type.MakeGenericType:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消