2017-04-12 7 views
0

レガシーコードを扱うときに時々私は私がアプリケーションを通過するモックする必要がある巨大なオブジェクトを取得... 200のようなプロパティのツール

代わりに増築の持つオブジェクトオブジェクトを手動で私は値を入力してC#クラスから模擬XMLオブジェクトを生成する方法がありますか?たとえば:

public Class Animal 
{ 
    public bool hasWings {get; set;} 
    public string name {get; set;} 
    public int numberOfFeet {get; set;} 
} 

に変わるだろう:私は実際に実際の値を必要としない

<Animal> 
    <hasWings>true</hasWings> 
    <name>string</name> 
    <numberOfFeet>0</numberOfFeet> 
</Animal> 

は...ちょうど

感謝をプレースホルダ!

答えて

1

以下の方法を使用してジョブを完了できます。値を記入し、デフォルトでこれは、オブジェクトを作成します。 更新:を追加しました再帰呼び出しをいくつかの制限があります

private static object GetDummyObject(Type type) 
{ 
    var obj = Activator.CreateInstance(type); 
    if (obj != null) 
    { 
     var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); 

     foreach (var property in properties) 
     { 
      if (property.PropertyType == typeof(String)) 
      { 
       property.SetValue(obj, property.Name.ToString(), null); 
      } 
      else if (property.PropertyType.IsArray) 
      { 
       property.SetValue(obj, Array.CreateInstance(type.GetElementType(), 0), null); 
      } 
      else if (property.PropertyType.IsClass) 
      { 
       var ob = GetDummyObject(property.PropertyType); 
       property.SetValue(obj, ob, null); 
      } 
      else 
      { 
       var o = GetDefault(property.PropertyType); 
       property.SetValue(obj, o, null); 
      } 
     } 
    } 

    return obj; 
} 

public static object GetDefault(Type type) 
{ 
    return Activator.CreateInstance(type); 
} 

クラス型のプロパティを処理します。これは、デフォルトコンストラクタのオブジェクトのみを生成しますが、いつでもそれを拡張できます。

XMLが必要な場合は、このメソッドから返されたオブジェクトをただシリアル化してください。

+0

いいね、GetDefaultとは何ですか? VSはメソッドを要求しています。 –

+0

Getmethodは、Activator.CreateInstance(property.PropertyType)を囲む単なるラッパーです。ラインを交換して、あなたは行かなければなりません。 – vendettamit

+0

nice ... that works ...あなたのソリューションを再帰的に拡張して、大きなクラスのオブジェクトにドリルダウンして値を設定できるようにしています...サブクラスがある場合はヌル参照例外を取得します –