我在实现泛型的父子接口时遇到了问题。目前最好的答案是:这是不可能的,但我也没有找到其他人问过完全相同的问题。我希望只是因为我不知道正确的语法,以使编译器理解我的意图。以下是我试图实现的代码示例(已经简化)。
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接口而没有错误。问题出在祖先类Group上,试图实现I_Group接口时出现了错误。
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中起作用。当子类不是泛型时,它可以工作,这让我想到必须存在一些语法来正确编译它。我做错了什么吗?这可行吗?如果不行,有人能帮我理解为什么吗?
public partial class Segment : I_Segment<I_Complex>
,会发生什么? - chtenbI
和名称之间加下划线,这是一种不好的编程风格。 - Felix K.