[英]C# generic - Can I refer to an implement of an interface inside it?
我有一些這樣的代碼:
public interface Base<TImpl, T1>
where TImpl : Base<TImpl, T1>
{
public T1 Build(TImpl arg);
}
public class Impl1 : Base<Impl1, int>
{
public int Value { get; set; }
public int Build(Impl1 arg)
{
return arg.Value;
}
}
public class Impl2 : Base<Impl2, string>
{
public string Value { get; set; }
public string Build(Impl2 arg)
{
return arg.Value;
}
}
TImpl
通用參數對我來說似乎很丑陋。 我是否有機會安全地刪除TImpl
部分,或刪除T1, T2...
並且可以編寫類似public TImpl.C1 Method(TImpl arg);
?
這將是Curiously recurring template pattern 的一個例子。 當只有一個實現類時,這沒有多大意義。
這種模式的重點是確保Impl.Method
的參數也是Impl
。 在提供相同級別的類型安全性的同時,沒有任何簡單的方法可以避免這種模式。
Eric Lippert 是 C# 背后的架構師之一,他在一篇關於這個主題的文章中指出,雖然該模式有一些潛在的用途,但它也有問題(感謝 Matthew Watson 指出)。 並得出結論:
我的建議是,在用 C# 實現這種奇怪的模式之前,要仔細考慮; 給客戶帶來的好處真的超過了你給代碼維護者帶來的精神負擔所帶來的成本嗎?
您也可以始終忽略類型安全,而只是獲取和返回對象,但我不建議這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.