实现一个泛型类,其中定义在基接口类型上,但实现在从该基派生的接口上
本文关键字:实现 接口类型 接口 派生 定义 一个 泛型类 | 更新日期: 2023-09-27 18:30:07
在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
但我不确定这是否能回答你的问题。。。