[英]How can I implement a factory to return a type that implements a generic interface, without knowing the generic type ahead of time?
[英]How can I return a class instance with a generic type as an interface with a generic type?
当我有一个简单的类和接口时,可以执行以下操作:
public class Foo : IFoo
{
public IFoo Instance()
{
return this;
}
}
当两者都是泛型时,有没有办法做同样的事情?
public class Base<T, TI>
{
public TI Instance()
{
return this; // Nope
return (T) this; // Nope
}
}
public class Foo : Base<Foo, IFoo>
{
}
但是,我尝试执行此操作,但出现“无法隐式转换类型”错误。
C#不支持此功能。
你能做的最好的就是
public class Base<T, TI> where T : Base<T, TI>, TI
{
public TI Instance()
{
return (TI) (object) this; // Yep
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.