[英]Inheritance from generic interfaces
I don't know how to solve a problem with generic interfaces. 我不知道如何解决通用接口的问题。
Generic interface represents factory for objects: 通用接口表示对象的工厂:
interface IFactory<T>
{
// get created object
T Get();
}
Interface represents factory for computers (Computer class) specyfing general factory: 接口代表工厂的计算机(计算机类)specyfing一般工厂:
interface IComputerFactory<T> : IFactory<T> where T : Computer
{
// get created computer
new Computer Get();
}
Generic interface represents special factory for objects, which are cloneable (implements interface System.ICloneable): 通用接口表示对象的特殊工厂,可以克隆(实现接口System.ICloneable):
interface ISpecialFactory<T> where T : ICloneable, IFactory<T>
{
// get created object
T Get();
}
Class represents factory for computers (Computer class) and cloneable objects: 类表示计算机(计算机类)和可克隆对象的工厂:
class MyFactory<T> : IComputerFactory<Computer>, ISpecialFactory<T>
{
}
I get compiler error messages In MyFactory class: 我在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'.
Not sure if this is a typo, but should this: 不确定这是不是一个错字,但应该这样:
interface ISpecialFactory<T>
where T : ICloneable, IFactory<T>
have really been 真的
interface ISpecialFactory<T> : IFactory<T>
where T : ICloneable
Really, I think this is probably what you're trying to do: 真的,我认为这可能是你想要做的:
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();
}
}
Live example: http://rextester.com/ENLPO67010 实例: http : //rextester.com/ENLPO67010
Try this this code block: 试试这个代码块:
class MyFactory<T> : IComputerFactory<Computer>, ISpecialFactory<T>
where T: ICloneable, IFactory<T>
{
}
I guess your definition of ISpecialFactory<T>
is incorrect. 我猜你的
ISpecialFactory<T>
定义是不正确的。 Change it to: 将其更改为:
interface ISpecialFactory<T> : IFactory<T>
where T : ICloneable
{
// get created object
T Get();
}
You possibly don't want the T
type to implement IFactory<T>
! 您可能不希望
T
类型实现IFactory<T>
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.