在c#中动态查找变量
本文关键字:查找 变量 动态 | 更新日期: 2023-09-27 18:26:40
这里我刚刚得到了一个场景:这里我要做的是声明5个字符串变量并分配null,其中第一个数组得到了字符串变量名称的列表,第二个数组包含了需要分配给以下声明的5个字符串的值:
string slot1=null,slot2=null,slot3=null,slot4=null,slot5=null;
string[] a=new string[5]{slot1,slot2,slot3,slot4,slot5};
string[] b=new string[5]{abc,def,ghi,jkl,mno};
for(int i=0;i<a.length;i++)
{
//here i want to do is dynamically find the variable (for ex. slot1) or you can say a[i] and assign the value from b[i] (for ex. abc) to it.
}
如何实现这一点?????
string slot1 = null, slot2 = null, slot3 = null, slot4 = null, slot5 = null;
string[] a = new string[5]{slot1,slot2,slot3,slot4,slot5};
string[] b = new string[5]{abc,def,ghi,jkl,mno};
for(int i=0; i<a.length; i++)
{
FieldInfo prop = this.GetType().GetField(a[i]);
if(prop!=null) prop.SetValue(this, b[i]);
}
希望这能有所帮助。。。。谢谢
您正在寻找这样的东西:参考文献:1
public static void Main()
{
string[] a= new string[5]{"Slot1","Slot2","Slot3","Slot4","Slot5"};
string[] b= new string[5]{"abc","def","ghi","jkl","mno"};
var whatever = new Whatever();
for(int i = 0; i < a.Length; i++)
{
var prop = a[i];
var value = b[i];
Console.WriteLine(prop);
var propertyInfo = whatever.GetType().GetProperty(prop);
Console.WriteLine(propertyInfo);
if(propertyInfo != null) propertyInfo.SetValue(whatever, value,null);
}
Console.WriteLine(whatever.ToString());
}
public class Whatever {
public string Slot1{get;set;}
public string Slot2{get;set;}
public string Slot3{get;set;}
public string Slot4{get;set;}
public string Slot5{get;set;}
public override string ToString(){
return "Slot 1 : " + Slot1 + "'n" +
"Slot 2 : " + Slot2 + "'n" +
"Slot 3 : " + Slot3 + "'n" +
"Slot 4 : " + Slot4 + "'n" +
"Slot 5 : " + Slot5 ;
}
}