'casting' with reflection

前端 未结 6 1831
面向向阳花
面向向阳花 2020-11-30 21:47

Consider the following sample code:

class SampleClass
{
    public long SomeProperty { get; set; }
}

public void SetValue(SampleClass instance, decimal valu         


        
6条回答
  •  醉酒成梦
    2020-11-30 22:31

    Thomas answer only works for types that implement IConvertible interface:

    For the conversion to succeed, value must implement the IConvertible interface, because the method simply wraps a call to an appropriate IConvertible method. The method requires that conversion of value to conversionType be supported.

    This code compile a linq expression that does the unboxing (if needed) and the conversion:

        public static object Cast(this Type Type, object data)
        {
            var DataParam = Expression.Parameter(typeof(object), "data");
            var Body = Expression.Block(Expression.Convert(Expression.Convert(DataParam, data.GetType()), Type));
    
            var Run = Expression.Lambda(Body, DataParam).Compile();
            var ret = Run.DynamicInvoke(data);
            return ret;
        }
    

    The resulting lambda expression equals to (TOut)(TIn)Data where TIn is the type of the original data and TOut is the given type

提交回复
热议问题