[英]Why does a generic class implementing a generic interface with type constraints need to repeat these constraints?
假設我有一個以下的C#界面:
public interface IInterface<T> where T : SomeClass
{
void InterfaceMethod();
}
而SomeClass的定義如下:
public class SomeClass
{
public void SomeMethod();
}
現在我想定義接口的實現,它不會編譯:
public class InterfaceImpl<T> : IInterface<T>
{
public void InterfaceMethod()
{
T test = default(T);
test.SomeMethod(); //Gives Error
}
}
在我改為之前:
public class InterfaceImpl<T> : IInterface<T> where T : SomeClass
{
public void InterfaceMethod()
{
T test = default(T);
test.SomeMethod(); //Compiles fine
}
}
從界面中類型約束是否也“繼承”(不是正確的詞,我知道)是否有意義?
該類不需要重復這些約束,它需要提供滿足接口約束的類型。 有幾種方法可以做到:
關鍵的是, T
在InterfaceImpl<T>
屬於InterfaceImpl
,以便被放置在任何約束T
必須InterfaceImpl
自身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.