簡體   English   中英

使用屬性索引C#添加到列表屬性

[英]Add to List Property using the properties Index C#

我想使用一個foreach循環來添加到ac#列表中,而不使用列表屬性鍵名。

我有一個清單,例如

public class Bus 
{
    public string Val1 { get; set; }
    public string Val2 { get; set; }
    public string Val3 { get; set; }
    public string Val4 { get; set; }
    public string Val5 { get; set; }
    public string Val6 { get; set; }

    // ...

    public string Val127 { get; set; }
}

我要填充的列表可以具有200多個屬性,因此我試圖找到一種無需寫入屬性即可快速填充它們的方法。 我想使用這樣的東西從一維數組(線)填充它

j = 0
for (int i = 0; i < lines.Length; i++)
{
    foreach(Bus BusProp in BusList)
    {
        BusProp[j] = line[i+j];
        j =+ 1;
    }
}

這是行不通的。 任何建議表示贊賞

為什么不使用

public class Bus
{
    public string[] Val = new string[127];
}

j = 0;
for (int i = 0; i<lines.Length; i++)
{
    foreach(Bus BusProp in BusList)
    {
        BusProp.Val[j] = line[i + j];
        j =+ 1;
    }
}

如果您不能更改類定義,則主要的替代選擇是使用反射。

void Main()
{
  var bus = new Bus();
  var data = new string[6] { "A", "B", "C", "D", "E", "F" };

  for (var i = 1; i <= 6; i++)
  {
    bus.GetType().GetProperty("Val" + i.ToString()).SetValue(bus, data[i - 1]);
  }

  Console.WriteLine(bus.Val5); // E
}

public class Bus 
{
  public string Val1 {get;set;}
  public string Val2 {get;set;}
  public string Val3 {get;set;}
  public string Val4 {get;set;}
  public string Val5 {get;set;}
  public string Val6 {get;set;}
}

不用說,這是相當昂貴的,並且可能難以維護。 在使用此選項之前,請確保您沒有更合理的選擇(例如,更改類以包含數組而不是索引屬性,使用代碼生成...)。

即使您的數據庫具有150個索引列,它們具有某些類似於COBOL的怪物,但您的應用程序不能以Item[34]而不是Item34的形式處理它們的原因也不應該-將應用程序代碼與固定代碼隔離開您不滿意的限制。

嘗試這個

var typ = typeof(Bus);

var prop = typ.GetProperty($“ Val {j}”);

我覺得到目前為止的答案還沒有滿足您的需求,因此這是我的解決方案:

    static void Main(string[] args)
    {
        //Create a string array containing the desired property names, in this case I'll use a loop
        List<string> DesiredProperties = new List<string>(); 

        for (int i = 0; i < 100; i++)
        {
            DesiredProperties.Add(string.Format("Property{0}", i));
        }

        //Call the method that returns the object and pass the array as parameter
        var Bus = CreateDynamicObject(DesiredProperties);

        //Display one of the properties
        Console.WriteLine(Bus.Property99);
        Console.Read();
    }
    private static dynamic CreateDynamicObject(List<string> PropertyList)
    {
        dynamic obj = new System.Dynamic.ExpandoObject();
        foreach (string Prop in PropertyList)
        {
            //You can add the properties using a dictionary. You can also give them an initial value
            var dict = (IDictionary<string, object>)obj;
            dict.Add(Prop, string.Format("The value of {0}", Prop));
        }
        return obj;
    }

這段代碼將為var“ Bus”添加100個屬性,可以隨意訪問和應用值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM