[英]Assign List value to a class properties
I have an ordered list and would like to assign those value to a class. 我有一个有序列表,想将这些值分配给一个类。
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
}
any other methods instead of below method 任何其他方法,而不是下面的方法
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
If the properties are to be assigned in alphabetical order, you could use reflection to assign the values: 如果要按字母顺序分配属性,则可以使用反射来分配值:
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
}
}
You can try reflection class as following: 您可以尝试以下反射类:
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]);
}
}
}
In GetFields() method, please notice binding flags. 在GetFields()方法中,请注意绑定标志。 Use Nonpublic for Private variables.
对专用变量使用Nonpublic。
You can achieve this using reflection 您可以使用反射来实现
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.