gpt4 book ai didi

c# - 从通用接口(interface)继承

转载 作者:太空狗 更新时间:2023-10-29 18:16:20 25 4
gpt4 key购买 nike

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

通用接口(interface)代表对象的工厂:

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

接口(interface)代表计算机工厂(Computer类)specyfing通用工厂:

interface IComputerFactory<T> : IFactory<T> where T : Computer
{
// get created computer
new Computer Get();
}

通用接口(interface)表示对象的特殊工厂,这些对象是可克隆的(实现接口(interface) 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();
}
}

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

关于c# - 从通用接口(interface)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15569018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com