变量赋值环境下如何避免调用冗余
本文关键字:何避免 调用 冗余 赋值 环境 变量 | 更新日期: 2023-09-27 18:15:44
我经常(就像现在)这样写c#(或vb.net)代码:
someObject.field_1 = doSomething(
anotherObject_1.propertyA,
anotherObject_1.propertyB);
someObject.field_2 = doSomething(
anotherObject_2.propertyA,
anotherObject_2.propertyB);
// some more field in same schema.
someObject.field_X = doSomething(
anotherObject_X.propertyA,
anotherObject_X.propertyB);
Edit: anotherObject_1 ..anotherObject_X有相同的类型;someObject和anotherObject的类型通常不相同。
问题是扩展性和可维护性。新字段使我编写了几乎相同的代码,只是在对象命名方面略有不同。
With将逻辑封装在doSomething(..)我避免了逻辑冗余,但调用冗余仍然很烦人。
是否有一种方法(例如模式或。net(4.0)语言结构)来避免这种情况?
可以将set操作封装成不同的方法
void SetField(ref int field, object anotherObjectX)
{
field = doSmth(anotherObjectX...);
}
SetField(ref object.field1, anotherObject1);
SetField(ref object.field2, anotherObject2);
SetField(ref object.field3, anotherObject3);
但是您仍然需要为每个新字段添加新行
你可以使用反射来减少代码重复。如果知道你的目标属性总是被称为"propertyA"answers"propertyB",你可以很容易地使用反射并根据需要获取/设置它们的值。你也可以传入你的对象,并在那里用反射操作它。
例如,你可以这样写(注意:语法没有完全检查):
public someReturnType DoSomething(object myObject)
{
if (null == myObject)
{
throw new ArgumentNullException("myObject");
}
var propertyA = myObject.GetType().GetProperty("propertyA");
if (null == propertyA)
{
//this object doesn't have any property called "propertyA".
//throw some error if needed
}
var value = propertyA.GetValue(myObject); //You will need to cast as proper expected type
// You can retrieve propertyB similarly by searching for it through GetProperty call.
// Once you have both A and B,
// you can work with values and return your output as needed.
return something;
}