C#中如何传入一个字符串参数作为静态变量名 根据字符串调用不同的静态变量。

比如
public void Method(String a,int b)
{
Form1.a=b;
}
有两个静态变量 一个是abc 另一个是asd 传入abc就调用Form.abc 传入asd就调用Form.asd
请问怎么样才能做到。

阅读 4.9k
3 个回答

搜索关键字:反射, reflection

public class MyClass
{
    public int Property1 { get; set; }
}
static void Main()
{
    MyClass tmp_Class = new MyClass();
    tmp_Class.Property1 = 2;
    Type type = tmp_Class.GetType(); //获取类型
    System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1"); //获取指定名称的属性
    int value_Old = (int)propertyInfo.GetValue(tmp_Class, null); //获取属性值
    Console.WriteLine(value_Old);
    propertyInfo.SetValue(tmp_Class, 5, null); //给对应属性赋值
    int value_New = (int)propertyInfo.GetValue(tmp_Class, null);
    Console.WriteLine(value_New);    
}

参考一下,不过这个不是静态属性。

为什么不 试试 使用 Dictionary呢?

static Dictionary<string,int> DIC = new Dictionary<string,int>(){
    {"hello",0}
    // etc 
}
pubic void Method(string key,int value){
    if(DIC.ContainsKey(key)){
        DIC[key] = value;
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进