C#泛型方法并返回从xml在方法中创建的参数化类型的对象

the*_*rrs 4 .net c# generics types

我有一个方法,我想返回参数化类型T ie的对象实例.Foo<T>.

类型T在方法中使用GetType()XML文件中的字符串元素进行实例化.由于类或方法在创建之前都不知道它,我也无法参数化.

有没有办法可以Foo<T>从非泛型方法返回一个类型的对象?

编辑:这是一个方法签名,如:

 public Foo<T> getFooFromXml(string name) {
Run Code Online (Sandbox Code Playgroud)

在里面创建类型的地方,方法和类都是非泛型的?

Jos*_*osh 8

是的,基本上你必须得到开放的泛型类型并创建一个封闭的泛型类型.

Type openType = typeof(Foo<>);
Type closedType = openType.MakeGenericType(typeof(string));

return Activator.CreateInstance(closedType); // returns a new Foo<string>
Run Code Online (Sandbox Code Playgroud)

编辑:注意我上面使用了typeof(Foo <>),我故意将尖括号留空.