Expression.ArrayAccess () on IDictionary <string, object> by key name
How do I create an expression tree to read a value on an array access for IDictionary<string,object>
?
I want to present:
((IDictionary<string,object>)T)["KeyName"]
I cannot find an example of using ArrayAccess for string name access. I need something like:
var parameterExpression = Expression.Parameter(typeof(IDictionary<string, object>)); var paramIndex = Expression.Constant("KeyName"); var arrayAccess = Expression.ArrayAccess(parameterExpression, paramIndex);
I am getting the error this is not an array. What is the correct way to do this?
+3
source share
1 answer
You might * want to access the property Item
:
var dic = new Dictionary<string, object> { {"KeyName", 1} }; var parameterExpression = Expression.Parameter(typeof (IDictionary<string, object>), "d"); var constant = Expression.Constant("KeyName"); var propertyGetter = Expression.Property(parameterExpression, "Item", constant); var expr = Expression.Lambda<Func<IDictionary<string, object>, object>>(propertyGetter, parameterExpression).Compile(); Console.WriteLine(expr(dic));
If you pulled the hood in the class using the indexer, there is a property Item
. Consider this example:
class HasIndexer { public object this[int index] { get { return null; } } }
has the following (applies to indexers) IL:
.property instance object Item( int32 index ) { .get instance object ConsoleApplication8.HasIndexer::get_Item(int32) } .method public hidebysig specialname instance object get_Item ( int32 index ) cil managed { // Method begins at RVA 0x2050 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: ret } // end of method HasIndexer::get_Item
+5
source share