c# - 输入来自 InvalidCastException 的数据

标签 c# types .net

问题很简单:有没有办法从 InvalidCastException 中获取有问题的 System.Type?我希望能够以“Expected {to-type}; found {from-type}”等格式显示有关失败类型转换的信息,但我找不到访问所涉及类型的方法。

编辑: 我需要能够访问所涉及的类型的原因是因为我有一段时间有关于较短名称的信息。例如,我想说的不是类型 RFSmallInt,而是类型实际上是 smallint。而不是错误信息

Unable to cast object of type 'ReFactor.RFSmallInt' to type 'ReFactor.RFBigInt'.

我其实是想展示

Expected bigint; recieved smallint.

最佳答案

一个解决方案可能是实现一个 Cast 函数,如果转换不成功,它会为您提供该信息:

static void Main(string[] args)
{
    try
    {
        string a = Cast<string>(1);
    }
    catch (InvalidCastExceptionEx ex)
    {
        Console.WriteLine("Failed to convert from {0} to {1}.", ex.FromType, ex.ToType);
    }
}



public class InvalidCastExceptionEx : InvalidCastException
{
    public Type FromType { get; private set; }
    public Type ToType { get; private set; }

    public InvalidCastExceptionEx(Type fromType, Type toType)
    {
        FromType = fromType;
        ToType = toType;
    }
}

static ToType Cast<ToType>(object value)
{
    try
    {
        return (ToType)value;
    }
    catch (InvalidCastException)
    {
        throw new InvalidCastExceptionEx(value.GetType(), typeof(ToType));
    }
}

关于c# - 输入来自 InvalidCastException 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18195221/

相关文章:

c# - System.Threading.Timer最大 dueTime 值问题

c# - 假脱机Observable.FromEvent生成的正在进行的项目

reactjs - 绑定(bind)元素 'title' 隐式具有 'any' 类型

types - 有没有一种很好的方法可以在 Go 中模拟 "Maybe"或 "option"类型?

c# - 检查指定日期何时发生的最佳方法

c# - Web 应用程序的三种不同类型的用户

c# - 如何告诉 MVVMLight 创建一个新的 View 模型?

scala - Scala 中的基本集合类型是什么?

.net - 如何退出 VSTO 加载项

c# - 如何检查复选框状态是否已更改