let's say I have these classes :
internal class A
{
public B Field { get; set; }
}
internal class B
{
public int SubField { get; set; }
}
Is it possible to do something like this :
var a = new A();
a.Field = new B();
a.Field.SubField = 10;
dynamic d = a;
var path = "Field.SubField";
var i = d.path; // How to look for field <Field.SubField开发者_如何学Python> instead of field <path>?
You can do this with reflection.
static object ReflectOnPath(object o, string path) {
object value = o;
string[] pathComponents = path.Split('.');
foreach (var component in pathComponents) {
value = value.GetType().GetProperty(component).GetValue(value, null);
}
return value;
}
There is absolutely no error checking in the above; you'll have to decide how you want to do that.
Usage:
var a = new A();
a.Field = new B();
a.Field.SubField = 10;
string path = "Field.SubField";
Console.WriteLine(ReflectOnPath(a, path));
You could even make this an extension method so that you can say
Console.WriteLine(a.ReflectOnPath("Field.SubField"));
It is not possible to do what you want using dynamic. dynamic just isn't intended for that.
First, think what the behaviour should be if you do:
dynamic d = a;
var path = "Field.SubField";
var i = d.path
and class A has for its own a field "path".
Trying to access a.Field.Subfield by means of a.path (which means a."FieldSubfield") it's just syntactically incorrect. If you want to achieve this, Jason wrote a very nice example of how you can do it (through reflection).
精彩评论