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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.