从封闭的泛型中提取泛型类型
我想要这样的东西:
class Foo<T>{...}
class Boo<T>{
Queue<T> stuff = new Queue<T>();
public void Boo(Foo<T>){...};
}
...
//Extract the generic type - string - to define the type
//of MyBoo.
var MyBoo = new Boo(new Foo<string>());
我收到错误消息通用类型'Boo'需要'1'类型参数.是的,我通过明确说明模板类型来解决此问题,但我想知道是否存在/可以提取该类型的方法隐式键入,而不必显式声明.
I get the error "generic type 'Boo' requires '1' type arguments. Ya, I fixed the problem by stating the template type explicitly, but I'd like to know if there was/is a way to extract that type implicitly, rather than having to state it explicitly.
该其他帖子可能相关,但我不确定.
您不能直接使用泛型类型的构造函数隐式地执行此操作,但是可以使用泛型方法,例如在非泛型类中:
You can't do it implicitly directly with the constructor of a generic type, but you could from a generic method, e.g. in a non-generic class:
public static class Boo
{
public Boo<T> Create<T>(Foo<T> foo)
{
return new Boo<T>(foo);
}
}
然后:
// myBoo will be inferred to be of type Boo<string>
var myBoo = Boo.Create(new Foo<string>());
当然,没有是另一个名为Boo
的类-可能是完全不同的东西,并且可能是其他东西的实例方法:
Of course, it doesn't have to be another class called Boo
- it could be something completely different, and it could be an instance method of something else:
var factory = new BooFactory();
var myBoo = factory.Create(new Foo<string>());
重要的一点是,它是通用的方法-类型参数可以针对通用方法进行推断,而不能针对通用类型进行推断.
The important point is that it's a generic method - type arguments can be inferred for generic methods, but not for generic types.