C#: Dynamic runtime cast

前端 未结 9 2210
情深已故
情深已故 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:10

    The opensource framework Dynamitey has a static method that does late binding using DLR including cast conversion among others.

    dynamic Cast(object obj, Type castTo){
        return Dynamic.InvokeConvert(obj, castTo, explict:true);
    }
    

    The advantage of this over a Cast called using reflection, is that this will also work for any IDynamicMetaObjectProvider that has dynamic conversion operators, ie. TryConvert on DynamicObject.

提交回复
热议问题