Stack Overflow Asked by Node.JS on December 17, 2020
I am stuck trying to make the dictionary values generic in the following code. I would like to use Expression
as a dictionary key and not Expression<Action>
. If I change the code to use Expression
I get an error. It would be great if the solution would involve Expression.Convert
so I would not be trying to make an Expression
generic by adding Action
as a generic parameter.
Expression<Action> test = () => Console.WriteLine("Hello world");
var dict = new Dictionary<string, Expression<Action>> {["foo"] = test};
var functionDef = Expression.Property(Expression.Constant(dict), "Item", Expression.Constant("foo"));
var intermediate = Expression.Lambda(functionDef);
Expression.Invoke(Expression.Invoke(Expression.Constant(intermediate)));
Error if I use generic Expression
instead of Expression<Action>
as a dictionary type:
Unhandled exception. System.ArgumentException: Expression of type ‘System.Linq.Expressions.Expression’ cannot be invoked (Parameter ‘expression’)
I'm not sure what you're issue here is, but maybe you don't need expressions.
Here is an expression-less example:
var d = new Dictionary<string, Action<string>>()
{
{ "hello", name => Console.WriteLine($"Hello {name}") },
{ "bye", name => Console.WriteLine($"Bye {name}!. Have a great day!") }
};
d["hello"]("Node.JS");
d["bye"]("Node.JS");
This prints:
Hello Node.JS
Bye Node.JS!. Have a great day!
Answered by tymtam on December 17, 2020
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP