如何通过lambda表达式传递属性?

我的项目中有一些unit testing,我们希望能够设置一些具有私有设置器的属性。 目前我正在通过reflection和这种扩展方法来做到这一点:

public static void SetPrivateProperty(this object sourceObject, string propertyName, object propertyValue) { sourceObject.GetType().GetProperty(propertyName).SetValue(sourceObject, propertyValue, null); } 

假设我有一个像这样的TestObject:

 public class TestObject { public int TestProperty{ get; private set; } } 

然后我可以在我的unit testing中调用它,如下所示:

 myTestObject.SetPrivateProperty("TestProperty", 1); 

但是,我想在编译时validation属性名称,因此我希望能够在via表达式中传递属性,如下所示:

 myTestObject.SetPrivateProperty(o => o.TestProperty, 1); 

我怎样才能做到这一点?

C#6.0 新手 : nameof (property)

如果getter是公共的,则以下内容应该有效。 它将为您提供一个如下所示的扩展方法:

 var propertyName = myTestObject.NameOf(o => o.TestProperty); 

它需要一个公共吸气剂。 我希望,在某些时候,像这样的reflectionfunction已经融入到语言中。

 public static class Name { public static string Of(LambdaExpression selector) { if (selector == null) throw new ArgumentNullException("selector"); var mexp = selector.Body as MemberExpression; if (mexp == null) { var uexp = (selector.Body as UnaryExpression); if (uexp == null) throw new TargetException( "Cannot determine the name of a member using an expression because the expression provided cannot be converted to a '" + typeof(UnaryExpression).Name + "'." ); mexp = uexp.Operand as MemberExpression; } if (mexp == null) throw new TargetException( "Cannot determine the name of a member using an expression because the expression provided cannot be converted to a '" + typeof(MemberExpression).Name + "'." ); return mexp.Member.Name; } public static string Of(Expression> selector) { return Of(selector); } public static string Of(Expression> selector) { return Of(selector as LambdaExpression); } } public static class NameExtensions { public static string NameOf(this TSource obj, Expression> selector) { return Name.Of(selector); } }