Ho cercato su google l'argomento e ho anche cercato la SO. C'è un sacco di soluzioni che tutte loro (che ho trovato) non sono state completate. Potete aiutarmi per favore, per impostare le proprietà di una classe e le proprietà della sua proprietà nidificata, scelte da una lambda
, usando 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;
}
}
e nel consumatore, voglio essere in grado di:
Parent t = new Parent();
t.Set<int>(t => t.Number, 6)
.set<string>(t => t.Name, "something")
.Set<int>(t => t.Nested.Id, 25);
Qualcosa di simile dovrebbe funzionare:
public class Parent
{
public Parent Set<TValue>(Expression<Func<Parent, TValue>> func, TValue value)
{
MemberExpression mex = func.Body as MemberExpression;
if(mex == null) throw new ArgumentException();
var pi = mex.Member as PropertyInfo;
if(pi == null) throw new ArgumentException();
object target = GetTarget(mex.Expression);
pi.SetValue(target, value, null);
return this;
}
private object GetTarget(Expression expr)
{
switch (expr.NodeType)
{
case ExpressionType.Parameter:
return this;
case ExpressionType.MemberAccess:
MemberExpression mex = (MemberExpression)expr;
PropertyInfo pi = mex.Member as PropertyInfo;
if(pi == null) throw new ArgumentException();
object target = GetTarget(mex.Expression);
return pi.GetValue(target, null);
default:
throw new InvalidOperationException();
}
}
}