2

我经常(就像现在一样)来写这样的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);

编辑: anotherObject_1 .. anotherObject_X 具有相同的类型;someObject 和 anotherObject 通常具有不同的类型。

问题是可扩展性和可维护性。新领域使我可以编写几乎相同的代码,而对象命名几乎没有区别。

通过将逻辑封装在 doSomething(..) 中,我避免了逻辑冗余,但调用冗余仍然很烦人。

有没有办法(例如模式或.Net(4.0)语言结构)来避免这种情况?

4

2 回答 2

3

您可以将集合操作封装到不同的方法中

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);

但您仍然需要为每个新字段添加新行

于 2013-05-29T05:26:57.377 回答
1

您可以使用反射来减少代码重复/重复。如果知道您的目标属性将始终称为“propertyA”和“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;
}
于 2013-05-29T05:33:02.107 回答