Determine if a reflected type can be cast to another reflected type

前端 未结 5 1192
我在风中等你
我在风中等你 2021-01-21 08:07

In .net (C#), If you have two types discovered through reflection is it possible to determine if one can be cast to the other? (implicit and/or explicit).

What I\'m tryi

5条回答
  •  萌比男神i
    2021-01-21 08:34

    public static bool HasConversionOperator( Type from, Type to )
            {
                Func bodyFunction = body => Expression.Convert( body, to );
                ParameterExpression inp = Expression.Parameter( from, "inp" );
                try
                {
                    // If this succeeds then we can cast 'from' type to 'to' type using implicit coercion
                    Expression.Lambda( bodyFunction( inp ), inp ).Compile();
                    return true;
                }
                catch( InvalidOperationException )
                {
                    return false;
                }
            }
    

    This should do the trick for implicit and explicit conversions (including numeric types, classes, etc.)

提交回复
热议问题