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 に答える