我有很多具有以下属性的类:
class C1
{
[PropName("Prop1")]
public string A {get;set;}
[PropName("Prop2")]
public string B {get;set;}
[PropName("Prop3")]
public string C {get;set;}
}
class C2
{
[PropName("Prop1")]
public string D {get;set;}
[PropName("Prop2")]
public string E {get;set;}
[PropName("Prop3")]
public string F {get;set;}
}
该属性告诉实际属性是什么,但 C# 属性的名称并不总是匹配。在 C1 和 C2 的情况下,C1.A 与 C2.D 具有相同的属性。
这些类不是任何继承链的一部分,我无法控制它们,因此我无法更改它们。
“Prop1”,“Prop2”,...,“PropN”有一些常见的操作。在没有太多代码重复但仍使其可维护的情况下编写这些操作的最佳解决方案是什么?
解决方案 #1(if 语句 - 很多)
void OperationWithProp1(object o)
{
string prop1;
C1 class1 = o as C1;
if (class1 != null)
prop1 = class1.A;
C2 class2 = o as C2;
if (class2 != null)
prop1 = class2.D;
// Do something with prop1
}
解决方案#2(重载 - 很多)
void OperationWithProp1(string prop1)
{
// Do something with prop1
}
void RunOperationWithProp1(C1 class1)
{
OperationWithProp1(class1.A);
}
void RunOperationWithProp1(C2 class2)
{
OperationWithProp1(class2.D);
}
解决方案#3(反射)-我担心性能,因为这些操作中的每一个都会被调用数千次,并且有数百个操作
void OperationWithProp1(object o)
{
// Pseudo code:
// Get all properties from o that have the PropName attribute
// Look if any attribute matches "Prop1"
// Get the value of the property that matches
// Do something with the value of the property
}
您会选择哪种解决方案,为什么?你有其他的模式吗?
编辑澄清:
很多类意味着几十个
很多属性意味着 30-40 个属性/类