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/