我有很多带有属性的类,例如:
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”等具有一些常见操作。最好的解决方案是什么,可以在不重复过多代码的情况下编写这些操作,同时仍然使其可维护。
解决方案#1(如果语句-很多)
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个属性
PropertyInfo
实例,以加快速度。 - Federico Berasateguidynamic
对象也有一些缓存)编辑:也许我误解了你。 :) 我今天思维混乱! - Chris Sinclair