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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/919169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:12:01  来源:igfitidea点击:

C# Generics methods and returning a object of a parameterized type created in the method from xml

c#.netgenericstypes

提问by theringostarrs

I have a method where I would like to return an object instance of parameterized type T ie. Foo<T>.

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

The type T is instantiated within the method using GetType(), from a string element in an XML file. Since neither the class or method knows about it before it is created, I cant parameterize either.

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

Is there a way I can return an object of type Foo<T>from the non-generic method?

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

EDIT: That is a method signature such as:

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

 public Foo<T> getFooFromXml(string name) {

where the type is created inside, and the method and class are both non-generic?

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

采纳答案by Josh

In response to your edit:

回应您的编辑:

That method signature isn't valid anyway. You need to know T at compile time in order to return Foo from a method. Consider my suggestion in the comments on my last answer where you would have a separate interface IFoo that Foo implements.

无论如何,该方法签名是无效的。您需要在编译时知道 T 才能从方法中返回 Foo。考虑我在上一个答案的评论中的建议,您将拥有一个单独的接口 IFoo Foo 实现。

class Foo<T> : IFoo {

   public T DoSomething() {
       ...
   }

   object IFoo.DoSomething() {
      return DoSomething();
   }

}

interface IFoo {
   object DoSomething();
}

回答by Josh

Yeah, basically you have to get the open generic type and create a closed generic type.

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

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

return Activator.CreateInstance(closedType); // returns a new Foo<string>

EDIT: Note that I used typeof(Foo<>) above, I intentionally left the angle brackets empty.

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