如何解决如何在基类中扩展开关案例动态属性获取器?
我有一个基类,该基类可获取如下所示的属性,以在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
。
在不复制粘贴整个开关盒的情况下,如何做到这一点?
解决方法
我不想用字符串索引器将您的基类概念与在属性字典中存储其他值相矛盾。这不是最好的方法,但是我过去也已经遇到过这种解决方案。
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];
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。