-1

是否可以在 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

如果我不能在派生接口上实现泛型,那么我需要对现有应用程序进行大量修改。是否有某种简单的方法来实现这一点?

4

1 回答 1

4

如果T1将接口的类​​型参数声明IC为协变

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

然后你可以将一个实例分配给一个C<IB>类型的变量IC<IA>

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

但我不确定这是否能回答你的问题......

于 2013-09-03T18:28:52.573 回答