简体   繁体   English

从名称中获取对象

[英]Get Object from its name

I have an object: 我有一个对象:

MyObject obj = new MyObject();
obj.X = "Hello";
obj.Y = "World";

Someone passes me a string: 有人给我传递了一个字符串:

string myString = "obj.X";

I want to get the value referenced to myString, like this: 我想获取引用到myString的值,如下所示:

var result = <Some Magic Expression>(myString); // "Hello"    

Is it possible through reflection? 通过反射有可能吗?

You can't exactly replicate this behaviour, because names of local variables aren't saved in the method's metadata. 您无法完全复制此行为,因为局部变量的名称未保存在方法的元数据中。 However, if you keep a dictionary of objects, you can address the object by its key: 但是,如果保留对象字典,则可以通过其键来寻址对象:

public static object GetProperty(IDictionary<string, object> dict, string path)
{
    string[] split = path.Split('.');
    object obj = dict[split[0]];
    var type = obj.GetType();
    return type.InvokeMember(split[1], BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.GetProperty, null, obj, null);
}

var dict = new Dictionary<string, object>();
var cl = new MyClass();
dict["obj"] = cl;
cl.X = "1";
cl.Y = "2";
Console.WriteLine(GetProperty(dict, "obj.X"));
Console.WriteLine(GetProperty(dict, "obj.Y"));

This can handle accessing fields and properties in the format "name.property". 这可以处理“名称。属性”格式的访问字段和属性。 Doesn't work for dynamic objects. 对动态对象无效。

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

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