gpt4 book ai didi

c# - 如何使用子泛型接口(interface)实现泛型接口(interface)

转载 作者:行者123 更新时间:2023-11-30 17:03:08 25 4
gpt4 key购买 nike

当父/子接口(interface)都是通用的时,我在实现父/子接口(interface)时遇到了问题。我能找到的最佳答案是不可能,但我也找不到其他人问完全相同的问题。我希望我只是不知道让编译器理解我正在尝试做的事情的正确语法。这是我尝试实现的代码的精简示例。

public interface I_Group<T>
where T : I_Segment<I_Complex>
{
T Segment { get; set; }
}

public interface I_Segment<T>
where T : I_Complex
{
T Complex { get; set; }
}

public interface I_Complex
{
string SomeString { get; set; }
}

public partial class Group : I_Group<Segment>
{
private Segment segmentField;

public Group() {
this.segmentField = new Segment();
}

public Segment Segment {
get {
return this.segmentField;
}
set {
this.segmentField = value;
}
}
}

public partial class Segment : I_Segment<Complex> {

private Complex complexField;

public Segment() {
this.complexField = new Complex();
}

public Complex Complex {
get {
return this.c_C001Field;
}
set {
this.c_C001Field = value;
}
}
}

public partial class Complex : I_Complex {

private string someStringField;

public string SomeString {
get {
return this.someStringField;
}
set {
this.someStringField = value;
}
}
}

所以在这里,Complex 是孙子,它实现了 I_Complex 而没有错误。 Segment 是它的父级,它实现 I_Segment 没有错误。问题出在尝试实现 I_Group 的祖 parent 组。我得到错误

The type 'Segment' cannot be used as type parameter 'T' in the generic type or method 'I_Group<T>'. There is no implicit reference conversion from 'Segment' to 'I_Segment<I_Complex>'.

我被引导相信这是协变性的问题,但我也被引导相信这是应该在 C# 4.0 中工作的东西。这在 child 不是通用的时候有效,这让我认为必须存在一些语法才能正确编译。难道我做错了什么?这可能吗?如果不是,有人可以帮助我理解为什么不是吗?

最佳答案

您可以将第二个泛型类型参数添加到 I_Group 接口(interface)声明中:

public interface I_Group<T, S>
where T : I_Segment<S>
where S : I_Complex
{
T Segment { get; set; }
}

并在 Group 类声明中明确指定这两种类型:

public partial class Group : I_Group<Segment, Complex>

它会让你的代码通过编译。

关于c# - 如何使用子泛型接口(interface)实现泛型接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18937645/

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