gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:51:34 24 4
gpt4 key购买 nike

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/

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