我有Builder,让我们看看代码:
public abstract class UISchemaBuilderBase
{
protected readonly UISchemaSpecification UiSchemaSpecification;
public UISchemaSpecification Builder() =>
UiSchemaSpecification;
public virtual UISchemaBuilderBase AddBoolean(
string fieldName,
string groupName = null)
{
.. some logic
UiSchemaSpecification.Properties[ fieldName ] = schema;
return this;
}
}
public class UISchemaBuilder : UISchemaBuilderBase
{
public UISchemaBuilder() : base(new UISchemaSpecification()) { }
public UISchemaGroupBuilder StartGroup(string name)
{
UiSchemaSpecification.ParsecMetadata ??= new();
UiSchemaSpecification.ParsecMetadata.Groups ??= new();
UiSchemaSpecification.ParsecMetadata.Groups.Add( new(name) );
return new UISchemaGroupBuilder(name, this, UiSchemaSpecification);
}
}
public class UISchemaGroupBuilder : UISchemaBuilderBase
{
private readonly string _name;
private readonly UISchemaBuilder _schemaBuilder;
public UISchemaGroupBuilder(
string name,
UISchemaBuilder schemaBuilder,
UISchemaSpecification specification)
: base(specification)
{
_name = name;
_schemaBuilder = schemaBuilder;
}
public override UISchemaGroupBuilder AddBoolean(
string fieldName,
string fieldTitle,
string groupName = null)
{
base.AddBoolean(fieldName, fieldTitle, _name);
return this;
}
public UISchemaBuilder EndGroup() =>
_schemaBuilder;
}
因此实现的代码允许执行此操作:
var builder = new UISchemaBuilder()
.StartGroup("groupName")
.AddBoolean()
.EndGroup()
.StartGroup("anotherGroupName")
.AddBoolean()
.EndGroup()
.Build();
问题是:我不能在 netstandard 中做同样的事情,而且我不明白如何解决这个问题。
我应该更改 UISchemaGroupBuilder 中方法的返回类型。例如,AddText
应返回 UISchemaBuilderBase
,而不是 UISchemaGroupBuilder
。
但如果我遵循这些建议,我的构建器就无法工作。例如,我无法在 AddBoolean
之后使用 EndGroup
。
有人可以帮我吗?
最佳答案
根据 this article about C# versions from Microsoft :
.NET Standard 2.1 C# - 8.0
.NET Standard 2.0 C# - 7.3
但是covariant return types
是 C# 9 的一部分,因此它与 .Net 标准不兼容。
与以前的语言版本相比,重写方法中的协变返回类型需要在 CLR 中进行更改,因此它与 .Net Framework 和 .Net Standard 中不兼容。
在OP示例中,组构建器的AddBool
方法可以是非虚拟方法,只是一个隐藏基类层次结构中方法的重载方法:
public class UISchemaGroupBuilder : UISchemaBuilderBase
{
...
public new UISchemaGroupBuilder AddBoolean(
string fieldName,
string fieldTitle,
string groupName = null)
{
base.AddBoolean(fieldName, fieldTitle, _name);
return this;
}
关于c# - 如何修复 "Target runtime doesn' t 支持覆盖中的协变类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76730192/