我有两种类型sourceType
和targetType
,需要用C#编写一个方法,检查sourceType
的值是否可以赋给targetType
的变量。该函数的签名为MatchResultTypeAndExpectedType(Type sourceType, Type targetType)
。
继承关系由IsAssignableFrom处理。对于可转换的类型,我考虑使用CanConvertFrom,但是例如,如果两种类型都是数字,则它总是返回false
。
我执行的测试:
TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(Decimal));
Console.WriteLine("Int16 to Decimal - " + typeConverter.CanConvertFrom(typeof(Int16)));
Console.WriteLine("UInt16 to Decimal - " + typeConverter.CanConvertFrom(typeof(UInt16)));
typeConverter = TypeDescriptor.GetConverter(typeof(long));
Console.WriteLine("UInt16 to Int64 - " + typeConverter.CanConvertFrom(typeof(uint)));
typeConverter = TypeDescriptor.GetConverter(typeof(Double));
Console.WriteLine("UInt16 to Double - " + typeConverter.CanConvertFrom(typeof(UInt16)));
typeConverter = TypeDescriptor.GetConverter(typeof(String));
Console.WriteLine("UInt16 to String - " + typeConverter.CanConvertFrom(typeof(UInt16)));
结果如下:
Int16 to Decimal - False
UInt16 to Decimal - False
UInt16 to Int64 - False
UInt16 to Double - False
UInt16 to String - False
[编辑] 我的问题是:在 .NET 中有没有一种方法可以检查是否可以将给定类型的值分配给另一个类型的变量,而不知道值,例如是否隐式转换会成功? MatchResultTypeAndExpectedType(Type sourceType, Type targetType)
的实现有以下更具体的要求:
- 源类型和目标类型在编译时未知,因为它们的程序集稍后加载。
- 不能提供任何值或对象作为输入。
- 不能在实现中创建类型的任何对象,因为系统的其余部分不允许该操作。只能创建值类型的值。
- 只需检查隐式转换。
已知sourceType
是否为值类型。 因此,这个方法的签名可以像这样:MatchResultTypeAndExpectedType(Type sourceType, Boolean isSourceValueType, Type targetType)
一种方法是实现隐式数字转换表,但它无法涵盖其他转换或用户定义的转换。