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

查看:17
本文介绍了将对象转换为 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?

推荐答案

问题是你没有cast一个 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 并调用 IConvertible.ToInt32,从 参考来源:

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天全站免登陆