.NET : How do you get the Type of a null object?

前端 未结 12 1284
暗喜
暗喜 2020-11-28 13:59

I have a method with an out parameter that tries to do a type conversion. Basically:

public void GetParameterValue(out object destination)
{
    object param         


        
12条回答
  •  星月不相逢
    2020-11-28 14:50

    So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.

    Not necessarily. The best that you can say is that it is an object. A null reference does not point to any storage location, so there is no metadata from which it can make that determination.

    The best that you could do is change it to be more generic, as in:

    public void GetParameterValue(out T destination)
    {
        object paramVal = "Blah";
        destination = default(T);
        destination = Convert.ChangeType(paramVal, typeof(T));
    }
    

    The type of T can be inferred, so you shouldn't need to give a type parameter to the method explicitly.

提交回复
热议问题