How can I determine if an implicit cast exists in C#?

后端 未结 3 1464
予麋鹿
予麋鹿 2021-02-18 13:16

I have two types, T and U, and I want to know whether an implicit cast operator is defined from T to U.

I\'m aware of the existence of IsAssignableFrom, and this is not

3条回答
  •  一生所求
    2021-02-18 14:07

    Here's a solution I found. The major code shown as bellow (after some simple translation):

    public static bool IsImplicitFrom(this Type type, Type fromType) {
        if (type == null || fromType == null) {
            return false;
        }
    
        // support for reference type
        if (type.IsByRef) { type = type.GetElementType(); }
        if (fromType.IsByRef) { fromType = type.GetElementType(); }
    
        // could always be convert to object
        if (type.Equals(typeof(object))) {
            return true;
        }
    
        // check if it could be convert using standard implicit cast
        if (IsStandardImplicitFrom(type, fromType)) {
            return true;
        }
    
        // determine implicit convert operator
        Type nonNullalbeType, nonNullableFromType;
        if (IsNullableType(type, out nonNullalbeType) && 
            IsNullableType(fromType, out nonNullableFromType)) {
            type = nonNullalbeType;
            fromType = nonNullableFromType;
        }
    
        return ConversionCache.GetImplicitConversion(fromType, type) != null;
    }
    
    internal static bool IsStandardImplicitFrom(this Type type, Type fromType) {
        // support for Nullable
        if (!type.IsValueType || IsNullableType(ref type)) {
            fromType = GetNonNullableType(fromType);
        }
    
        // determine implicit value type convert
        HashSet typeSet;
        if (!type.IsEnum && 
            ImplicitNumericConversions.TryGetValue(Type.GetTypeCode(type), out typeSet)) {
            if (!fromType.IsEnum && typeSet.Contains(Type.GetTypeCode(fromType))) {
                return true;
            }
        }
    
        // determine implicit reference type convert and boxing convert
        return type.IsAssignableFrom(fromType);
    }
    

    Update: Here's the whole file.

提交回复
热议问题