Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

Casting object to int throws InvalidCastException in C#

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...