[英]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.