[英]C# Generics - a generic type constraint
我具有以下通用类型层次结构:
interface IGenericInterface<TId, TValue>
{…}
class A : IGenericInterface<long, string>
我想设计一个以IGenericInterface作为类型的通用类型。 编译器允许的解决方案是:
class SomeType<TType, TId, TValue> where TType : IGenericInterface<TId, TValue>
当我需要继承这样的类型时,我需要指定:
class Derived : SomeType<A, long, string>
由于第二个类已经是IGenericInterface<long, string>
,因此这似乎是指定第二和第三类型参数的冗余。
有没有一种方法可以实现我想要的-优雅的派生类?
您可以添加一个中间接口,并SomeType
约束。 就像是:
interface IA : IGenericInterface<long,string> { }
class A : IA {}
class SomeType<TType> where TType : IA { }
class Derived : SomeType<A> { }
您说得对,您的观点很明智,很遗憾, 目前尚不支持。 您所追求的就是被称为高级种类的参数多态性 ,这是函数式编程爱好者急切想要的功能。
这样的帮助吗? (我认为IEnumerable
做类似的事情)
internal interface IGenericInterface
interface IGenericInterface <TId, TValue> : IGenericInterface
class SomeType<TType> where TType : IGenericInterface
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.