c# - 类型 'TNestedInterface' 必须可转换为 'INestedInterfaceTest' 才能将其用作参数 'TNestedInterface'

标签 c# generics recursion interface

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 接口(interface)。 我在这里缺少什么?

以下确实有效,没有递归接口(interface)实现:

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/

相关文章:

python从递归方法返回列表

c# - 如果同一文件夹中有多个项目或多个 .cs 文件,如何编译 dotnet 项目

c++ - C++ 中有 "generics-like"功能吗?

java - 如何从linkedList中递归删除一个项目?

Java-使用递归展平数组

c# - 在 C# 中是否有等同于 typedef 的东西?

c# - 无法创建 SSL/TLS 安全通道。安全通道故障

c# - 将 bool 属性绑定(bind)到 WinForm 的 BackColor 属性

c# - 如何在ViewModel中处理列表框keydown事件?

typescript `groupBy` 打字