使用反射,现在可以这样操作:line.Add(l => l.Length, 10)
或line.Add("Length", 10)
或line.Add(nameof(line.Length), 10)
(env> .net 4.5)
你也可以重复这样的特殊成员:(new List<string> { "Length", "Height" }).ForEach(p => line.Add(p, 10))
class Line
{
public int Length { get; set; }
public double Height { get; set; }
public void Add<O>(Expression<Func<Line, O>> accessor, dynamic scale) where O : struct
{
Add((accessor.Body as MemberExpression).Member.Name, scale);//simply get name from expression
}
public void Add(string name, dynamic scale)
{
var prop = typeof(Line).GetProperty(name);//can also get all members
dynamic a = prop.GetValue(this);
prop.SetValue(this, a * scale);
}
}
您可以使用动作<线,双>而不是创建一个新的代表 – aspark