将List值分配给类属性

时间:2014-08-27 04:03:44

标签: c#

我有一个有序列表,并希望将这些值分配给一个类。

List<string> listValue = new List<string>()
{
  "Hello",
  "Hello2",
  "Hello3",
}

public class SampleClass
{
  public string _VarA {get; set;}
  public string _VarB {get; set;}
  public string _VarC {get; set;}
  //around 40 attribute
}

任何其他方法而不是以下方法

SampleClass object = new SampleClass();
object._VarA = listValue.get(0);
object._VarB = listValue.get(1);
object._VarC = listValue.get(2);

//Sample
object._VarA = "Hello"
object._VarB = "Hello2"
object._VarC = "Hello3"
//until end of this class variable

3 个答案:

答案 0 :(得分:1)

如果要按字母顺序指定属性,则可以使用反射来指定值:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{

    public static void Main()
    {
        var listValue = new List<string>()
        {
            "Hello",
            "Hello2",
            "Hello3",
        };

        var sampleClass = new SampleClass();
        var sampleType = sampleClass.GetType();
        var properties = sampleType.GetProperties().OrderBy(prop => prop.Name).ToList();
        for (int i = 0; i < listValue.Count; i++)
        {
            if (i < properties.Count)
            {
                properties[i].SetValue(sampleClass, listValue[i]);
                Console.WriteLine(properties[i].Name + " = " + listValue[i]);
            }
        }
        Console.ReadLine();
    }

    public class SampleClass
    {
        public string _VarA { get; set; }
        public string _VarB { get; set; }
        public string _VarC { get; set; }
        //around 40 attribute
    }
}

答案 1 :(得分:1)

您可以尝试使用以下反射类:

class test
    {
        public string var1;
        public string var2;
        public string var3;
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<string> testList = new List<string>();
            testList.Add("string1");
            testList.Add("string2");
            testList.Add("string3");
            test testObj = new test();
            var members = testObj.GetType().GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            for (int i = 0; i < members.Length; i++)
            {
                members[i].SetValue(testObj, testList[i]);
            }
        }
    }

在GetFields()方法中,请注意绑定标志。将Nonpublic用于私有变量。

答案 2 :(得分:1)

您可以使用反射

来实现此目的
SampleClass obj = new SampleClass();
int i = 0;
foreach (var item in typeof(SampleClass).GetProperties())   // (or) obj.GetType().GetProperties()
{
    item.SetValue(obj, listValue[i++].ToString());
}