如何在基类中扩展switchcase动态属性getter



我有一个基类,它获取如下属性,以在JSON/C#名称之间进行映射:

[JsonPropertyName("foo")]
[DataMember(Name = "foo")]
public FooAttribute { get; set; }
[JsonPropertyName("bar")]
[DataMember(Name = "bar")]
public BarAttribute { get; set; }
public object? this[string attributeName]
{
get
{
switch (attributeName)
{
case "foo":
return FooAttribute;
case "bar":
return BarAttribute;
case ....

default:
try
{
return Attributes[attributeName];
}
catch (KeyNotFoundException)
{
return null;
}
}
}
}

但现在我想制作实现上述所有功能的派生类,并添加一些附加属性,如ChildA:spam : SpamAttribute和ChildB:eggs : EggsAttribute

如何在不复制粘贴整个开关盒的情况下实现这一点?

我不想用字符串索引器和在Attributes字典中存储附加值来反驳基类的概念。这不是最好的,但我过去也遇到过这种解决方案。

class Base
{
private IDictionary<string, object> Attributes = new Dictionary<string, object>(StringComparer.Ordinal);
public virtual object this[string attributeName]
{
get
{
switch (attributeName)
{
default:
Attributes.TryGetValue(attributeName, out var valueOrNull);
return valueOrNull;
}
}
}
}
class Descendant1 : Base
{
// ... FooAttribute and BarAttribute props here ...
public override object this[string attributeName]
{
get
{
switch (attributeName)
{
case "foo":
return FooAttribute;
case "bar":
return BarAttribute;
default:
return base[attributeName];
}
}
}
}
class Descendant2 : Descendant1
{
// ... BaconAttribute and EggsAttribute props here ...
public override object this[string attributeName]
{
get
{
switch (attributeName)
{
case "bacon":
return BaconAttribute;
case "eggs":
return EggsAttribute;
default:
return base[attributeName];
}
}
}
}

最新更新