C#: Dynamic runtime cast

前端 未结 9 2211
情深已故
情深已故 2020-11-27 03:50

I would like to implement a method with the following signature

dynamic Cast(object obj, Type castTo);

Anyone know how to do that? obj defi

9条回答
  •  无人及你
    2020-11-27 04:06

    You can use the expression pipeline to achieve this:

     public static Func Caster(Type type)
     {
        var inputObject = Expression.Parameter(typeof(object));
        return Expression.Lambda>(Expression.Convert(inputObject, type), inputPara).Compile();
     }
    

    which you can invoke like:

    object objAsDesiredType = Caster(desiredType)(obj);
    

    Drawbacks: The compilation of this lambda is slower than nearly all other methods mentioned already

    Advantages: You can cache the lambda, then this should be actually the fastest method, it is identical to handwritten code at compile time

提交回复
热议问题