public interface INestedInterfaceTest<TChildType>
    where TChildType : INestedInterfaceTest<TChildType>
{
     List<TChildType> children { get; set; }
}

public abstract class NestedInterfaceTest : INestedInterfaceTest<NestedInterfaceTest>
{
    public List<NestedInterfaceTest> children { get; set; }

    public TNestedInterface GetNestedInterface<TNestedInterface>()
        where TNestedInterface : NestedInterfaceTest, new()
    {
        return GateWay<TNestedInterface>.GetNestedInterface();
    }
}

public class GateWay<TNestedInterface>
    where TNestedInterface : class, INestedInterfaceTest<TNestedInterface>, new()
{
    public static TNestedInterface GetNestedInterface()
    {
        return new TNestedInterface();
    }
}


抽象类中的GetNestedInterface方法出错。
错误消息是:类型'TNestedInterface'必须可转换为'INestedInterfaceTest',以便在通用类'GateWay'中将其用作参数'TNestedInterface'。

但是...,我的抽象类NestedInterfaceTest实现了INestedInterfaceTest接口。
我在这里想念什么?

在没有递归接口实现的情况下,以下方法可以工作:

public interface INestedInterfaceTest
{
}

public abstract class NestedInterfaceTest : INestedInterfaceTest
{
    public List<NestedInterfaceTest> children { get; set; }

    public TNestedInterface GetNestedInterface<TNestedInterface>()
        where TNestedInterface : NestedInterfaceTest, new()
    {
        return GateWay<TNestedInterface>.GetNestedInterface();
    }
}

public class GateWay<TNestedInterface>
    where TNestedInterface : class, INestedInterfaceTest, new()
{
    public static TNestedInterface GetNestedInterface()
    {
        return new TNestedInterface();
    }
}


似乎在递归实现中出错。

最佳答案

您缺少对GetNestedInterface<>()的一般约束。更改为此:

public TNestedInterface GetNestedInterface<TNestedInterface>()
    where TNestedInterface :
        NestedInterfaceTest,
        INestedInterfaceTest<TNestedInterface>, // new
        new()
{
    return GateWay<TNestedInterface>.GetNestedInterface();
}


注意第二个约束是新的。

关于c# - 类型“TNestedInterface”必须转换为“INestedInterfaceTest”,才能用作参数“TNestedInterface”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19234353/

10-10 02:08