使用字符串(c#)从不同的脚本访问变量的值
本文关键字:脚本 访问 变量 字符串 | 更新日期: 2023-09-27 18:02:44
我有一个名为Receive的类,它有一个变量public int head=10例如。
在另一个名为Mover的类中,我将设置一个新的变量private Receive bodypart。
我想要的是取bodypart的head的值,而不使用bodypart命令。头,但带有字符串,例如:
string bodyname = "head";
int v = bodypart.bodyname;
我知道这不起作用,为什么,但我找不到另一种方法。我已经在寻找反思,但没有得到它,不知道这是否是最好的。
看起来您可以在这里使用Dictionary collection。例如:
// Receieve class inherits Dictionary. Use <string, object> if your values
// are of different types
class Receive : Dictionary<string, int> {}
class Mover
{
private Receive bodypart;
// assigns value to bodypart field
public Mover(Receive bodypart)
{
this.bodypart = bodypart;
}
// get element from bodypart using string argument
public int GetBodyPart(string name)
{
return bodypart[name];
}
}
class Class26
{
static void Main()
{
// instantiates collection
Receive res = new Receive();
// add elements to collection
res.Add("head", 5);
// instantiates Mover and pass collection as parameter to ctor
Mover m = new Mover(res);
// takes one element from collection
int a = m.GetBodyPart("head");
Console.WriteLine(a);
}
}
输出:5
反射将以这样的方式执行任务
using System.Reflection;
...
public class Receive {
// using public fields is a bad practice
// let "Head" be a property
public int Head {
get;
set;
}
// Bad practice
public int UglyHead = 5;
public Receive() {
Head = 10;
}
}
...
string bodyname = "Head";
Receive bodyPart = new Receive();
// Property reading
int v = (int) (bodyPart.GetType().GetProperty(bodyname).GetValue(bodyPart));
// Field reading
int v2 = (int) (bodyPart.GetType().GetField("UglyHead").GetValue(bodyPart));