2012-04-17 66 views
7

我的项目中有一些单元测试,我们希望能够设置一些具有私人设置器的属性。如何通过lambda表达式传递属性?

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; } 
} 

然后我可以在我的单元测试调用此如下:目前我通过反射和这个扩展方法做

myTestObject.SetPrivateProperty("TestProperty", 1); 

但是,我想在编译时验证属性名称,因此我希望能够通过通过表达式的属性,如下所示:

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

我该怎么做?

+0

什么是lambda表达式的目的是什么?提供编译时验证? – mellamokb 2012-04-17 14:46:39

+0

@mellamokb是的。如果还有其他方法可以做到这一点,我就是游戏。 – Sterno 2012-04-17 14:47:06

+0

请参阅http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression – phoog 2012-04-17 14:49:53

回答

9

如果吸气剂是公共的,那么以下应该起作用。它会给你一个看起来像这样的扩展方法:

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

它需要一个公共的getter。我希望在某种程度上,像这样的反射功能可以融入语言中。

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<TSource>(Expression<Func<TSource, object>> selector) 
    { 
     return Of<TSource, object>(selector); 
    } 

    public static string Of<TSource, TResult>(Expression<Func<TSource, TResult>> selector) 
    { 
     return Of(selector as LambdaExpression); 
    } 
} 

public static class NameExtensions 
{ 
    public static string NameOf<TSource, TResult>(this TSource obj, Expression<Func<TSource, TResult>> selector) 
    { 
     return Name.Of(selector); 
    } 
} 
相关问题