我用谷歌搜索了问题并搜索了 SO。有很多解决方案(我发现的)都没有完成。你能帮我设置一个类的属性及其嵌套属性的属性,由 a 选择lambda
,使用Reflection
?
public class Parent
{
public class Child
{
public int Id { get; set; }
}
public string Name { get; private set; }
public int Number {get; private set; }
public Child Nested { get; set; }
public Parent()
{
Nested = new Child();
}
public Test Set<TValue>(Expression<Func<???> func, TValue value)
{
// find the property name from expression
// set the property by value
return this;
}
}
在消费者中,我希望能够:
Parent t = new Parent();
t.Set<int>(t => t.Number, 6)
.set<string>(t => t.Name, "something")
.Set<int>(t => t.Nested.Id, 25);