Checking if a type supports an implicit or explicit type conversion to another type with .NET

前端 未结 4 583
生来不讨喜
生来不讨喜 2020-12-10 05:53

Imagine you\'ve been given two System.Type\'s and you want to determine if there is an implicit or explicit type conversion from one to the other.

Without specifica

相关标签:
4条回答
  • 2020-12-10 06:38

    Expression.Convert can look for a user-defined conversion operator, but unfortunately it will just throw an exception if none is found. You could use it like this:

    public static bool CanConvert(Type fromType, Type toType)
    {
        try
        {
            // Throws an exception if there is no conversion from fromType to toType
            Expression.Convert(Expression.Parameter(fromType, null), toType);
            return true;
        }
        catch
        {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 06:40

    You could try casting each one to the other and catching the exception

    0 讨论(0)
  • 2020-12-10 06:45

    I think Type.IsAssignableFrom should give you what you need.

    [edit] note that this does NOT consider conversion operators, so it's possible that this is not useful to you. Worth mentioning anyway.

    0 讨论(0)
  • 2020-12-10 06:55

    I don't think so. You'll have use reflection and look for those good ol' op_Implicit and op_Explicit static methods on each type.

    This brings up the very interesting question: which has a greater performance impact, reflection (this answer) or using exceptions for control flow (Quartermeister's)? I honestly couldn't guess. You might want to profile each and find out for yourself.

    0 讨论(0)
提交回复
热议问题