从通用接口继承

时间:2013-03-22 11:17:11

标签: c# generics inheritance interface

我不知道如何解决通用接口的问题。

通用接口表示对象的工厂:

interface IFactory<T>
{
    // get created object
    T Get();    
}

接口表示计算机(计算机类)的工厂,用于指定一般工厂:

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表示计算机(计算机类)和可复制对象的工厂:

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'.  

3 个答案:

答案 0 :(得分:9)

不确定这是否是拼写错误,但应该这样:

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();
    }
}

实例:http://rextester.com/ENLPO67010

答案 1 :(得分:3)

试试这个代码块:

class MyFactory<T> : IComputerFactory<Computer>, ISpecialFactory<T>
    where T: ICloneable, IFactory<T>
    {

    }

答案 2 :(得分:3)

我猜您对ISpecialFactory<T>的定义不正确。将其更改为:

interface ISpecialFactory<T> : IFactory<T>
    where T : ICloneable
{
    // get created object
    T Get();
}

您可能不希望T类型实现IFactory<T>