2012-04-17 16 views
7

Projemde, özel ayarlayıcıları olan bazı özellikleri ayarlayabileceğimiz bazı birim testleri var.Bir özelliği lambda ifadesiyle nasıl geçebilirim?

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

Böyle bir TestObject vardı varsayarsak: şu şekildedir:

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

o zaman benim birim testlerinde bu çağırabilirsiniz: Şu anda yansıma ve bu uzatma yöntemi ile yapıyorum

myTestObject.SetPrivateProperty("TestProperty", 1); 

Ancak, derleme zamanında özellik adının geçerliliğini almak istiyorum ve bu nedenle, şu şekilde ifade yoluyla özelliği iletmek istiyorum:

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

Bunu nasıl yapabilirim?

+0

lambda deyiminin amacı nedir? Derleme zamanı doğrulaması sağlamak için? – mellamokb

+0

@mellamokb Evet. Bunu yapmak için başka bir yol varsa, ben oyunum. – Sterno

+0

Bkz. Http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression – phoog

cevap

9

Alıcının herkese açık olması durumunda aşağıdakiler çalışmalıdır. Buna benzer bir uzantı yöntemi verecektir:

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

Herkese açık bir alıcı gerektirir. Umarım, bir noktada, bunun gibi yansıtma işlevleri dile aktarılır. C# 6.0

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); 
    } 
} 
İlgili konular