2017-06-24 5 views
0

私は1000個以上のパラメータを持つモデル・リストを持っているので、リストをいくつかの変数で埋める必要があります。私はこれを行うにはしたくないこと:C#リスト・キーとして変数を使用してオブジェクト・リストに要素を追加

   list.Add(new Model{ 
        name1= value, 
        name2= value, 
        ..... 
        name1000=value 
        }); 

私は、リスト内のパラメータの名前を含む配列を持っているので、私は名前の配列を使用することが可能であるならば不思議とループでました変数を次のように入力します。

   list.Add(new Model{ 
        //a loop? 
        array[0]= value 
        }); 

ありがとうございました。

+4

1000個の変数を持つモデルは、おそらくコードがエレガントに設計されていないことを示しています... –

答えて

0

これは反射を使用して達成できます。これらの多くのプロパティを持つモデルが最適ではないので、

public class ModelFactory 
{ 
    private IDictionary<string, PropertyInfo> propertiesInfo { get; set; } 

    public ModelFactory() 
    { 
     this.propertiesInfo = typeof(Model) 
          .GetProperties() 
          .ToDictionary(p => p.Name, p => p); 
    } 

    public Model Create(string[] propertiesToInitialize, dynamic value) 
    { 
     var model = new Model(); 
     foreach (var propertyName in propertiesToInitialize) 
     { 
      if (this.propertiesInfo.ContainsKey(propertyName)) 
      { 
       var property = this.propertiesInfo[propertyName]; 
       property.SetValue(model, value); 
      } 
     } 

     return model; 
    } 
} 

モデル以下のコードは

public class Model 
{ 
    public int MyProperty1 { get; set; } 

    public int MyProperty2 { get; set; } 

    public int MyProperty3 { get; set; } 

    public int MyProperty4 { get; set; } 

    public int MyProperty5 { get; set; } 
} 

使い方すでにコメントで述べたようにしかし

public void Test() 
{ 
    var propertiesToInitialize = new string[] { "MyProperty1", "MyProperty2", "MyProperty4" }; 
    var modelFactory = new ModelFactory(); 

    var list = new List<Model>(); 

    list.Add(modelFactory.Create(propertiesToInitialize, 500)); 

    Console.WriteLine("MyProperty1 " + list[0].MyProperty1); // 500 
    Console.WriteLine("MyProperty2 " + list[0].MyProperty2); // 500 
    Console.WriteLine("MyProperty3 " + list[0].MyProperty3); // 0 
    Console.WriteLine("MyProperty4 " + list[0].MyProperty4); // 500 
    Console.WriteLine("MyProperty5 " + list[0].MyProperty5); // 0 
} 

を初期化するために、お使いのモデルのデザインを再考してください。

+0

ここでは動的なポイントは何ですか? – MistyK

+0

@MistyKこの例では、動的の利点はありません。最初は、IDictionary PropertyValueToInitをパラメータとして使用して、ユーザーが異なる値を初期化できるようにしました。これは単なるサンプルコードです。 – Kaushal

関連する問題