[英]Inheritance from generic interfaces
我不知道如何解決通用接口的問題。
通用接口表示對象的工廠:
interface IFactory<T>
{
// get created object
T Get();
}
接口代表工廠的計算機(計算機類)specyfing一般工廠:
interface IComputerFactory<T> : IFactory<T> where T : Computer
{
// get created computer
new Computer Get();
}
通用接口表示對象的特殊工廠,可以克隆(實現接口System.ICloneable):
interface ISpecialFactory<T> where T : ICloneable, IFactory<T>
{
// get created object
T Get();
}
類表示計算機(計算機類)和可克隆對象的工廠:
class MyFactory<T> : IComputerFactory<Computer>, ISpecialFactory<T>
{
}
我在MyFactory類中收到編譯器錯誤消息:
The type 'T' cannot be used as type parameter 'T' in the generic type or method 'exer.ISpecialFactory<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'exer.IFactory<T>'.
The type 'T' cannot be used as type parameter 'T' in the generic type or method 'exer.ISpecialFactory<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.ICloneable'.
不確定這是不是一個錯字,但應該這樣:
interface ISpecialFactory<T>
where T : ICloneable, IFactory<T>
真的
interface ISpecialFactory<T> : IFactory<T>
where T : ICloneable
真的,我認為這可能是你想要做的:
public class Computer : ICloneable
{
public object Clone(){ return new Computer(); }
}
public interface IFactory<T>
{
T Get();
}
public interface IComputerFactory : IFactory<Computer>
{
Computer Get();
}
public interface ISpecialFactory<T>: IFactory<T>
where T : ICloneable
{
T Get();
}
public class MyFactory : IComputerFactory, ISpecialFactory<Computer>
{
public Computer Get()
{
return new Computer();
}
}
試試這個代碼塊:
class MyFactory<T> : IComputerFactory<Computer>, ISpecialFactory<T>
where T: ICloneable, IFactory<T>
{
}
我猜你的ISpecialFactory<T>
定義是不正確的。 將其更改為:
interface ISpecialFactory<T> : IFactory<T>
where T : ICloneable
{
// get created object
T Get();
}
您可能不希望T
類型實現IFactory<T>
!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.