Casting object to int throws InvalidCastException in C#

前端 未结 3 641
天涯浪人
天涯浪人 2020-12-03 22:54

I have this method:

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


        
3条回答
  •  余生分开走
    2020-12-03 23:23

    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.

提交回复
热议问题