繁体   English   中英

将列表值分配给类属性

[英]Assign List value to a class properties

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

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

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

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
    }
}

您可以尝试以下反射类:

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。

您可以使用反射来实现

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM