2012-04-17 13 views
7

मेरे प्रोजेक्ट पर कुछ यूनिट परीक्षण हैं जहां हम निजी सेटर्स वाले कुछ गुण सेट करने में सक्षम होना चाहते हैं।मैं लैम्ब्डा अभिव्यक्ति के माध्यम से एक संपत्ति कैसे पास कर सकता हूं?

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

लैम्ब्डा अभिव्यक्ति का उद्देश्य क्या है? संकलन-समय सत्यापन प्रदान करने के लिए? – mellamokb

+0

@mellamokb हां। अगर ऐसा करने का दूसरा साधन है, तो मैं खेल हूं। – Sterno

+0

देखें http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression – phoog

उत्तर

9

यदि गेटर सार्वजनिक है, तो निम्नलिखित कार्य करना चाहिए। यह आपको एक विस्तार विधि देगा जो इस तरह दिखता है:

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

इसके लिए एक सार्वजनिक गेटर की आवश्यकता है। मुझे आशा है कि, किसी बिंदु पर, इस तरह की प्रतिबिंब कार्यक्षमता भाषा में लुढ़क जाएगी।

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); 
    } 
} 
संबंधित मुद्दे