मैं लिंक अभिव्यक्तियों का उपयोग करके एक लैम्ब्डा अभिव्यक्ति बनाना चाहता हूं जो स्ट्रिंग इंडेक्स का उपयोग करके 'प्रॉपर्टी बैग' शैली शब्दकोश में किसी आइटम तक पहुंचने में सक्षम है। मैं नेट 4.लिंक अभिव्यक्तियों का उपयोग करके मैं एक शब्दकोश आइटम तक कैसे पहुंच सकता हूं
static void TestDictionaryAccess()
{
ParameterExpression valueBag = Expression.Parameter(typeof(Dictionary<string, object>), "valueBag");
ParameterExpression key = Expression.Parameter(typeof(string), "key");
ParameterExpression result = Expression.Parameter(typeof(object), "result");
BlockExpression block = Expression.Block(
new[] { result }, //make the result a variable in scope for the block
Expression.Assign(result, key), //How do I assign the Dictionary item to the result ??????
result //last value Expression becomes the return of the block
);
// Lambda Expression taking a Dictionary and a String as parameters and returning an object
Func<Dictionary<string, object>, string, object> myCompiledRule = (Func<Dictionary<string, object>, string, object>)Expression.Lambda(block, valueBag, key).Compile();
//-------------- invoke the Lambda Expression ----------------
Dictionary<string, object> testBag = new Dictionary<string, object>();
testBag.Add("one", 42); //Add one item to the Dictionary
Console.WriteLine(myCompiledRule.DynamicInvoke(testBag, "one")); // I want this to print 42
}
उपयोग कर रहा हूँ ऊपर परीक्षा पद्धति में, मैं परिणाम में शब्दकोश आइटम मूल्य अर्थात testBag [ "एक"] प्रदान करना चाहते हैं। ध्यान दें कि मैंने असाइन कॉल को प्रदर्शित करने के परिणामस्वरूप पारित कुंजी स्ट्रिंग को असाइन किया है।
धन्यवाद क्रिस, यह एक इलाज करता है। –