![](/img/trans.png)
[英]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.