gpt4 book ai didi

c# - 通过继承改变返回签名——多态

转载 作者:太空宇宙 更新时间:2023-11-03 20:47:18 24 4
gpt4 key购买 nike

只是想知道是否有任何方法可以执行以下操作:

public Interface IDataField 
{
object GetValue();
}

public Interface IComplexDataField : IDataField
{
object GetDefaultValue();
}

public class MyBase
{
private IDataField _DataField;

public MyBase()
{
this._DataField = this.CreateDataField();
}

public virtual IDataField CreateDataField()
{
return new DataField(); //Implements IDataField
}

**public virtual IDataField GetDataField()**
{
return this._DataField;
}

public void SomeMethod()
{
this.GetDataField().GetValue();
}
}


public class MyComplexBase : MyBase
{
public override IDataField CreateDataField()
{
return new ComplexDataField(); //Implements IComplexDataField which Implements IDataField
}

**public override IComplexDataField GetDataField()**
{
return (IComplexDataField)base.GetDataField();
}

public void SomeComplexSpecificMethod()
{
this.GetDataField().GetValue();
this.GetDataField().GetDefaultValue();
}
}

干杯安东尼

最佳答案

您想要的是返回类型的协方差。这在 C# 中不存在。

你能否使 MyBase 通用:

public class MyBase<T> where T : IDataField
{
public virtual T CreateDataField()
{
... etc ...
}
}

或者,您可以使用“new”重新声明该方法并隐藏基类方法。两者都不是特别吸引人......

关于c# - 通过继承改变返回签名——多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/266901/

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