Casting object to int throws InvalidCastException in C#

情到浓时终转凉″ 提交于 2019-11-26 17:16:44

问题


I have this method:

private static Dossier PrepareDossier(List<List<object>> rawDossier)
{
    return new Dossier((int)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?


回答1:


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

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

So the difference is that this:

int a = (int)obj;

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

int a = Convert.ToInt32(obj);

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

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);
}

You can see the unboxing on try roslyn:

IL_0007: unbox.any [mscorlib]System.Int32

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




回答2:


I would guess this is because the object in your list is not an int.

Convert.ToInt32 will convert other non-int types so works.

Check what is being passed in to the method.




回答3:


When you try to unbox int from an object, the boxed value should be int, otherwise you will receive an exception, while Convert.ToInt32 uses IConvertible implementation of boxed type to convert the value to int.

For example if the value which is boxed is string "100", unboxing it will throw an exception but using Convert.ToInt32, internally uses int.Parse.

Boxing and Unboxing (C# Programming Guide)

Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.



来源:https://stackoverflow.com/questions/39891504/casting-object-to-int-throws-invalidcastexception-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!