将对象转换为int会在C#中引发InvalidCastException [英] Casting object to int throws InvalidCastException in C#

查看:131
本文介绍了将对象转换为int会在C#中引发InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法:

private static Dossier PrepareDossier(List<List<object>> rawDossier)
{
    return new Dossier((int)rawDossier[0][0]);
}

当我使用它时,我得到一个InvalidCastException.但是,当我使用Convert.ToInt32(rawDossier[0][0])时,它可以正常工作.有什么问题吗?

When I use it I get an InvalidCastException. However, when I use Convert.ToInt32(rawDossier[0][0]) it works just fine. What is the problem?

推荐答案

问题是您没有将object投射 int,而是尝试 >取消装箱一个整数.

The problem is that you don't cast an object to an int, you're attempting to unbox an int.

该对象确实必须是一个int.不能只是可以转换为整数的任何东西.

The object really has to be an int. It cannot be just anything that can be converted to an int.

所以区别在于:

int a = (int)obj;

真的需要obj成为盒装int,而没有其他内容,

Really needs obj to be a boxed int, nothing else, whereas this:

int a = Convert.ToInt32(obj);

将执行ToInt32方法,该方法将尝试弄清到底发生了什么并做正确的事.

Will execute the ToInt32 method which will try to figure out what is really going on and do the right thing.

这里的正确的事情"是确保所讨论的对象实现 IConvertible 并调用

The "right thing" here is to ensure the object in question implements IConvertible and calling IConvertible.ToInt32, as is evident from the reference source:

public static int ToInt32(object value) {
    return value == null? 0: ((IConvertible)value).ToInt32(null);
}

您可以看到拆箱上尝试罗斯林:

IL_0007: unbox.any [mscorlib]System.Int32

结论:您要取消包装的对象不是int,而是可以转换为int的对象.

Conclusion: The object you're trying to unbox is not an int, but it is something that can be converted to an int.

这篇关于将对象转换为int会在C#中引发InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆