Sharing New up dgn Expression Tree di .NET Windows Store (Win8 app) RRS feed

  • Diskusi Umum

  • Rekans,

    just sharing pas bikin mini-MVVM framework in-house

    Ternyata Expression Tree di .NET for Windows Store masih se-powerful .NET Desktop, berikut compiled lambda untuk kode var x = new Object()  

    *lebih cepat dibanding .NET Reflection Activator.CreateInstance

    #region new Object() using Expression Tree!

    #region Delegates

    public delegate BaseViewModel InstanceCreator(params object[] args);


    public static InstanceCreator GetCreator(ConstructorInfo cInfo)


        Type type = cInfo.DeclaringType;

        ParameterInfo[] paramsInfo = cInfo.GetParameters();

        // parameter of type object[] named args

        ParameterExpression paramExpr = Expression.Parameter(typeof (object[]), "args");

        var argsExpr = new Expression[paramsInfo.Length];

        // get each arg from object[] args

        // and create SomeType arg expression

        // eg. (int parameterA)

        for (int i = 0; i < paramsInfo.Length; ++i)


            ConstantExpression index = Expression.Constant(i);

            Type argType = paramsInfo[i].ParameterType;

            BinaryExpression accessprExpr = Expression.ArrayIndex(paramExpr, index);

            UnaryExpression castExpr = Expression.Convert(accessprExpr, argType);

            argsExpr[i] = castExpr;


        // new Constructor(param1, param2, ...)

        NewExpression newExpr = Expression.New(cInfo, argsExpr);

        // create lambda in order to compile expression

        LambdaExpression lambda = Expression.Lambda(typeof (InstanceCreator), newExpr, paramExpr);

        var compiledLambda = (InstanceCreator) lambda.Compile();

        return compiledLambda;



    Sharing oleh: Zeddy Iskandar

    Best Regards,
    Agnes Sannie [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Kamis, 29 November 2012 08.00

Semua Balasan