6
Bir String indeksi kullanarak 'property bag' stili Dictionary içindeki bir öğeye erişebilen Linq Expressions kullanarak Lambda Expression oluşturmak istiyorum. Yukarıdaki deney yönteminde Linq Expressions kullanarak bir Dictionary Öğesi'ne nasıl erişirim
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
}
.NET 4.
kullanıyorum, ben sonuç sözlük öğe değerini yani testBag [ "bir"] atamak istiyoruz. Assign çağrısını göstermek için anahtar dizesine geçirilen sonucu atamış olduğumu unutmayın.
Teşekkürler Chris, bu bir tedavi. –