问题描述
假设您已经获得了两个 System.Type,并且您想确定是否存在从一个到另一个的隐式或显式类型转换.
Imagine you've been given two System.Type's and you want to determine if there is an implicit or explicit type conversion from one to the other.
在没有专门检查静态方法的情况下,是否有内置方法来确定该类型是否支持其中一种或这些转换?
Without specifically checking for the static methods is there a built in method to determine that the type supports either or these conversions?
我知道这是一个简短的问题,但我认为这个场景相对容易解释,如果不是,请告诉我.
I know this is a brief body to a question but I think the scenario is relatively easy to explain, let me know if not.
提前致谢,斯蒂芬.
推荐答案
表达式.Convert 可以查找用户定义的转换运算符,但不幸的是,如果找不到,它只会抛出异常.你可以这样使用它:
Expression.Convert can look for a user-defined conversion operator, but unfortunately it will just throw an exception if none is found. You could use it like this:
public static bool CanConvert(Type fromType, Type toType)
{
try
{
// Throws an exception if there is no conversion from fromType to toType
Expression.Convert(Expression.Parameter(fromType, null), toType);
return true;
}
catch
{
return false;
}
}
这篇关于使用 .NET 检查一个类型是否支持隐式或显式类型转换为另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!