知道类型A的变量是否可以转换为类型B.

Nem*_*ein 5 c# casting

我知道我可以(隐式地)将a转换int为a floatfloata double.
此外,我可以(显式)转换double为a float或a int.

这可以通过以下示例证明:

int i;
float f;

// The smaller type fits into the bigger one
f = i;

// And the bigger type can be cut (losing precision) into a smaller
i = (int)f;
Run Code Online (Sandbox Code Playgroud)

问题是这些类型不是从另一个继承的(int不是子类型,float反之亦然).
他们已经实现了隐式/显式转换运算符或类似的东西.如果没有,它的工作原理就像......

我的问题是:如何检查A类型的变量是否可以转换为B类型.

我试过i.GetType().IsAssignableFrom(f.GetType()),但Type.IsAssignableFrom(Type)只检查继承和接口(可能还有更多),但不检查已实现的转换操作符.
我试过i is floatf is int,但效果是一样的.

M.B*_*ock 1

对于隐式类型(intfloat等),您可以使用 aTypeConverter来确定a类型的变量是否可以转换为b类型。您可以使用 (System.ComponentModel) 的重载之一找到对适当类型转换器的引用TypeDescriptor.GetConverter

对于自定义或其他参考类型,我建议Type.IsAssignableFrom(如问题中所引用)。这种方法的正确使用是:

var implType = typeof(List<>);
if (typeof(IEnumerable).IsAssignableFrom(implType))
    Console.WriteLine("'{0}' is convertible to '{1}'", implType, typeof(IEnumerable));
Run Code Online (Sandbox Code Playgroud)

上面的示例将告诉您该类型是否List<T>可以转换为IEnumerable.