进一步阅读后进行编辑,修改后的问题更具体.
An is expression evaluates to true if the provided expression is
non-null, and the provided object can be cast to the provided type
without causing an exception to be thrown. Otherwise, the expression
evaluates to false.
这是下面的问题.
var test = (Int32)(Int16)1; // Non-null and does not cause an exception.
var test2 = (Int16)1 is Int32; // Evaluates false.
该文档还指出:
Note that the is operator only considers reference conversions, boxing
conversions, and unboxing conversions. Other conversions, such as
user-defined conversions, are not considered.
因此,我认为它在上面不起作用,因为它是用户定义的转换.
我如何检查是否可以将某些内容转换为其他类型,包括非参考/装箱/拆箱转换?
注意:在编写适用于所有类型(包括非引用类型(与as相比))的CastToOrDefault扩展的单元测试时,我发现了此问题.
基于Mike Precup的链接代码的重构答案
我清理了他的答案,因为我觉得它是用旧风格写的.另外,即使速度较慢,但当每个列表只是另一个列表的子集时,拥有一个包含许多重复值的表还是有点奇怪.因此,我改为使表递归.注意:如果该值为null,则ThrowIfNull仅引发ArgumentNullException.
private static readonly Dictionary<Type, IEnumerable<Type>> PrimitiveTypeTable = new Dictionary<Type, IEnumerable<Type>>
{
{ typeof(decimal), new[] { typeof(long), typeof(ulong) } },
{ typeof(double), new[] { typeof(float) } },
{ typeof(float), new[] { typeof(long), typeof(ulong) } },
{ typeof(ulong), new[] { typeof(uint) } },
{ typeof(long), new[] { typeof(int), typeof(uint) } },
{ typeof(uint), new[] { typeof(byte), typeof(ushort) } },
{ typeof(int), new[] { typeof(sbyte), typeof(short), typeof(ushort) } },
{ typeof(ushort), new[] { typeof(byte), typeof(char) } },
{ typeof(short), new[] { typeof(byte) } }
};
private static bool IsPrimitiveCastableTo(this Type fromType, Type toType)
{
var keyTypes = new Queue<Type>(new[] { toType });
while (keyTypes.Any())
{
var key = keyTypes.Dequeue();
if (key == fromType) { return true; }
if (PrimitiveTypeTable.ContainsKey(key)) { PrimitiveTypeTable[key].ToList().ForEach(keyTypes.Enqueue); }
}
return false;
}
/// <summary>
/// Determines if this type is castable to the toType.
/// This method does more than the is-operator and
/// allows for primitives and implicit/explicit conversions to be compared properly.
/// https://*.com/a/18256885/294804
/// </summary>
/// <param name="fromType">The type to cast from.</param>
/// <param name="toType">The type to be casted to.</param>
/// <returns>True if fromType can be casted to toType. False otherwise.</returns>
/// <exception cref="ArgumentNullException">Thrown if either type is null.</exception>
public static bool IsCastableTo(this Type fromType, Type toType)
{
// https://*.com/a/10416231/294804
return toType.ThrowIfNull().IsAssignableFrom(fromType.ThrowIfNull()) ||
fromType.IsPrimitiveCastableTo(toType) ||
fromType.GetMethods(BindingFlags.Public | BindingFlags.Static).Any(m =>
m.ReturnType == toType && m.Name == "op_Implicit" || m.Name == "op_Explicit");
}
解决方法:
同样从您链接的MSDN页面:
Note that the is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered.
由于为Int16和Int32类型定义的隐式转换不是引用转换,因此装箱转换或拆箱转换的结果均为false.
如果您想知道为什么它不是参考转换,请注意implicit reference conversions页上的以下内容:
Reference conversions, implicit or explicit, never change the referential identity of the object being converted. In other words, while a reference conversion may change the type of the reference, it never changes the type or value of the object being referred to.
由于类型正在更改,并且不仅仅是转换为超类,因此不将其视为引用转换.
编辑:要回答您在其中编辑的第二个问题,请查看this page.我将复制代码以供参考:
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(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;
}
}
该代码使用反射来检查是否存在任何隐式或显式强制转换.但是,反射方法不适用于基元,因此必须手动进行检查,因此字典中可能包含基元的强制转换.