如何判断A类是否可以隐式转换为B类

Jud*_*ngo 22 .net reflection type-conversion implicit-conversion

给定类型a和类型b,我如何在运行时确定是否存在从a到b的隐式转换?

如果这没有意义,请考虑以下方法:

public PropertyInfo GetCompatibleProperty<T>(object instance, string propertyName)
{
   var property = instance.GetType().GetProperty(propertyName);

   bool isCompatibleProperty = !property.PropertyType.IsAssignableFrom(typeof(T));
   if (!isCompatibleProperty) throw new Exception("OH NOES!!!");

   return property;   
}
Run Code Online (Sandbox Code Playgroud)

这是我想要工作的调用代码:

// Since string.Length is an int property, and ints are convertible
// to double, this should work, but it doesn't. :-(
var property = GetCompatibleProperty<double>("someStringHere", "Length");
Run Code Online (Sandbox Code Playgroud)

jas*_*son 25

请注意,这IsAssignableFrom并不能解决您的问题.你必须像这样使用Reflection.注意显式需要处理基元类型; 这些列表符合规范的§6.1.2(隐式数字转换).

static class TypeExtensions { 
    static Dictionary<Type, List<Type>> dict = new Dictionary<Type, List<Type>>() {
        { typeof(decimal), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char) } },
        { typeof(double), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
        { typeof(float), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
        { typeof(ulong), new List<Type> { typeof(byte), typeof(ushort), typeof(uint), typeof(char) } },
        { typeof(long), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(char) } },
        { typeof(uint), new List<Type> { typeof(byte), typeof(ushort), typeof(char) } },
        { typeof(int), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(char) } },
        { typeof(ushort), new List<Type> { typeof(byte), typeof(char) } },
        { typeof(short), new List<Type> { typeof(byte) } }
    };
    public static bool IsCastableTo(this Type from, Type to) { 
        if (to.IsAssignableFrom(from)) { 
            return true; 
        }
        if (dict.ContainsKey(to) && dict[to].Contains(from)) {
            return true;
        }
        bool castable = from.GetMethods(BindingFlags.Public | BindingFlags.Static) 
                        .Any( 
                            m => m.ReturnType == to &&  
                            (m.Name == "op_Implicit" ||  
                            m.Name == "op_Explicit")
                        ); 
        return castable; 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

用法:

bool b = typeof(A).IsCastableTo(typeof(B));
Run Code Online (Sandbox Code Playgroud)

  • @Jason:你应该将它命名为`IsCastableFrom`并反转参数以匹配类似框架方法的命名. (3认同)
  • 为什么不使用可枚举的任何扩展名? (2认同)
  • 隐式/显式运算符不仅可以在`from`类型上声明,还可以在`to`类型上声明.然后需要检查`to`和`from`类型的运算符的methodinfo的返回类型和参数类型. (2认同)

Han*_*ant 5

您需要考虑的隐含转换:

  • 身分
  • sbyte为short,int,long,float,double或decimal
  • byte to short,ushort,int,uint,long,ulong,float,double或decimal
  • short,int,float,double或decimal
  • ushort to int,uint,long,ulong,float,double或decimal
  • int到long,float,double或decimal
  • uint to long,ulong,float,double或decimal
  • long to float,double或decimal
  • ulong为float,double或decimal
  • char到ushort,int,uint,long,ulong,float,double或decimal
  • 漂浮加倍
  • 可空类型转换
  • 引用类型到对象
  • 派生类到基类
  • 实现接口的类
  • 基础接口的接口
  • 当数组具有相同维数时,数组到数组,存在从源元素类型到目标元素类型的隐式转换,源元素类型和目标元素类型是引用类型
  • System.Array的数组类型
  • IList <>的数组类型及其基接口
  • 将类型委托给System.Delegate
  • 拳击转换
  • 枚举类型为System.Enum
  • 用户定义的转换(op_implicit)

我假设你正在寻找后者.你需要编写类似于编译器的东西来覆盖所有这些东西.值得注意的是System.Linq.Expressions.Expression没有尝试这个专长.


Cha*_*ion 5

这个问题的公认答案处理了很多案例,但不是全部.例如,以下是一些未正确处理的有效强制转换/转换:

// explicit
var a = (byte)2;
var b = (decimal?)2M;

// implicit
double? c = (byte)2;
decimal? d = 4L;
Run Code Online (Sandbox Code Playgroud)

下面,我发布了此功能的替代版本,专门回答了IMPLICIT演员和转换的问题.有关更多详细信息,我用于验证它的测试套件以及EXPLICIT演员版本,请查看我关于该主题的帖子.

public static bool IsImplicitlyCastableTo(this Type from, Type to)
{
    // from http://www.codeducky.org/10-utilities-c-developers-should-know-part-one/ 
    Throw.IfNull(from, "from");
    Throw.IfNull(to, "to");

    // not strictly necessary, but speeds things up
    if (to.IsAssignableFrom(from))
    {
        return true;
    }

    try
    {
        // overload of GetMethod() from http://www.codeducky.org/10-utilities-c-developers-should-know-part-two/ 
        // that takes Expression<Action>
        ReflectionHelpers.GetMethod(() => AttemptImplicitCast<object, object>())
            .GetGenericMethodDefinition()
            .MakeGenericMethod(from, to)
            .Invoke(null, new object[0]);
        return true;
    }
    catch (TargetInvocationException ex)
    {
        return = !(
            ex.InnerException is RuntimeBinderException
            // if the code runs in an environment where this message is localized, we could attempt a known failure first and base the regex on it's message
            && Regex.IsMatch(ex.InnerException.Message, @"^The best overloaded method match for 'System.Collections.Generic.List<.*>.Add(.*)' has some invalid arguments$")
        );
    }
}

private static void AttemptImplicitCast<TFrom, TTo>()
{
    // based on the IL produced by:
    // dynamic list = new List<TTo>();
    // list.Add(default(TFrom));
    // We can't use the above code because it will mimic a cast in a generic method
    // which doesn't have the same semantics as a cast in a non-generic method

    var list = new List<TTo>(capacity: 1);
    var binder = Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(
        flags: CSharpBinderFlags.ResultDiscarded, 
        name: "Add", 
        typeArguments: null, 
        context: typeof(TypeHelpers), // the current type
        argumentInfo: new[] 
        { 
            CSharpArgumentInfo.Create(flags: CSharpArgumentInfoFlags.None, name: null), 
            CSharpArgumentInfo.Create(
                flags: CSharpArgumentInfoFlags.UseCompileTimeType, 
                name: null
            ),
        }
    );
    var callSite = CallSite<Action<CallSite, object, TFrom>>.Create(binder);
    callSite.Target.Invoke(callSite, list, default(TFrom));
}
Run Code Online (Sandbox Code Playgroud)