mercredi 13 juillet 2016

How do I declare a local dictionary in Expression

I want to fill a dictionary in Expression, but I always get an empty one. How can I fill it?

My code for now:

string[] bb = {"a", "b"};
Expression[] expressions = new Expression[bb.Length + 2];
var dict = Expression.New(typeof(Dictionary<string, object>));
expressions[0] = dict;
for (int i = 0; i < bb.Length; i++)
{
    var methodInfo = dict.Type.GetMethod("Add");
    expressions[i + 1] = Expression.Call(dict, methodInfo, Expression.Constant(bb[i], typeof(string)), Expression.Constant("hehehe", typeof(object)));
}
expressions[expressions.Length - 1] = Expression.Call(typeof (Bzzzz).GetMethod("Foo"), Expression.Constant("www.google.com"), dict);

var bodyExpression = Expression.Lambda
    (
        Expression.Block(expressions)
    );
var action = (Action) bodyExpression.Compile();
action();

Foo is not very interesting:

public static class Bzzzz
{
    public static void Foo(string uri, Dictionary<string, object> parameters)
    {
        Console.WriteLine(uri);
        if (parameters != null)
        foreach (var parameter in parameters)
        {
            Console.WriteLine($"{parameter.Key} = {parameter.Value}");
        }
    }
}


Okay, if you will.

I have a following method:

private static void ImplementMethod(TypeBuilder tb, MethodInfo imethod)
{
    var valueString = AsselbmyHolder.GetUriTemplate(imethod);
    var parameters = GetLamdaParameters(imethod);
    var local = Expression.Variable(typeof (Dictionary<string, object>));
    var ctor = local.Type.GetConstructor(new Type[0]);

    var bodyExpression = Expression.Lambda
        (
            Expression.Block(
                /* work */ ),
            parameters
        );

    var stub = bodyExpression.CompileToInstanceMethod(tb, imethod.Name, MethodAttributes.Public | MethodAttributes.Virtual);
    tb.DefineMethodOverride(stub, imethod);
}

Now in block I should convert parameters of MethodInfo into Dictionary<string, object>, where keys are parameter names, and values - their values respectively.





Aucun commentaire:

Enregistrer un commentaire