[英]C# Generic Type Inheritance
我有一個接口ICheese,我希望能夠根據需要進行擴展。 它包含在實現IFruit接口的類中:
public interface IFruit<T> where T : ICheese
{
T : cheese { get; }
}
這樣做是為了躲避C#沒有返回類型協方差的事實。 我希望能夠實現IFruit的任何實現,並且知道它內部具有某些版本的ICheese。
IFruit與許多涉及IFruit的ICracker進行了交談:
public interface ICracker<T> where T : ICheese
{
void Initialize(IFruit<T> fruit);
}
public abstract class Cracker<T> where T : ICheese
{
IFruit<T> fruit
public void Initialize(IFruit<T> fruit)
{
this.fruit = fruit;
}
}
只要ICracker的實現明確定義了它將使用哪種ICheese,它就可以工作:
public class Apple : IFruit<Cheddar> {/* Implementation of Class */}
public class Saltine : Cracker<Cheddar> {/* Implementation of Class */}
在那種情況下,在Saltine實例上調用Initialize(new Apple())是可行的。
但是,如果我們有這樣的ICracker:
public class Ritz : Cracker<ICheese> { /* Implementation of Class */ }
即使Cheddar繼承自ICheese,也無法將Apple傳遞到Rizt的Initialize()函數中。 有什么方法可以使我的工作生效,還是可以實現相同目標的模式? 基本想法是,我希望ICrackers能夠說“我至少需要此版本的ICheese”,並能夠接受至少提供該版本Icheese的任何IFruit。
您可以在T
中使IFruit
協變:
public interface IFruit<out T> where T : ICheese
{
T Cheese { get; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.