簡體   English   中英

實現一個泛型類,其中定義在基本接口類型上,但實現在從該基本接口派生的接口上?

[英]Implement a generic class where the definition is on a base interface type but the implementation is on an interface derived from that base?

是否可以在C#中實現泛型類,而該類的定義是在基本接口類型上,但實現是在從該基本接口派生的接口上?

我有一個具有核心功能的基本類型,但是我需要兩種不同的類型,具體取決於我的進程是使用數據數據還是使用整數數據。

我可以將基本類型設置為同時具有兩種數據類型,但我不希望這樣。

問題示例:

public interface IA {}

public interface IB : IA {}

public class CA : IA {}

public class CB : IB {}

public interface IC<T1> where T1 : IA { }

public class C<TIa> : IC<TIa> where TIa : IA {}

public class Thing
{
    public void Some()
    {
        IA a = new CB(); // fine IB is of type IA
        C<IB> b = new C<IB>(); // fine - obviously

        C<IB> y = new C<IA>(); // shouldn't work - doesn't work
        C<IA> x = new C<IB>(); // even though IB is of type IA this is not acceptable
    }
}

Cannot implicitly convert type 'ClassLibrary1.C<ClassLibrary1.IA>' to     
'ClassLibrary1.C<ClassLibrary1.IB>' // this makes sense

Cannot implicitly convert type 'ClassLibrary1.C<ClassLibrary1.IB>' to 
'ClassLibrary1.C<ClassLibrary1.IA>'  // this should work - IB derives from IA

如果我不能在派生接口上實現泛型,那么我將在現有應用程序上做大量的工作。 是否有某種簡單的方法來實現這一目標?

如果將接口IC的類型參數T1聲明為協變

public interface IC<out T1> where T1 : IA { }

那么您可以將C<IB>的實例分配給類型為IC<IA>的變量

IC<IA> x = new C<IB>(); // works

但我不確定這是否能回答您的問題...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM