简体   繁体   中英

PropertyInfo.GetValue(myObject, null).GetType() returns “Object reference not set to an instance of an object.”

I'm trying to convert a MembershipUserCollection to a DataSet to be used in a GridView and I have this helper class that will loop through all the membership rows and properties and get the values and types and shove them into DataRows.

It works while there is a value for the property, but when there is a null value, it breaks returning the message, "Object reference not set to an instance of an object.".

In this particular example, it breaks on the Comment field if when it's value is "null".

Here's my code where it occurs:

    foreach (PropertyInfo oPropertyInfo in PropertyInfos)
    {
        Type oType = oPropertyInfo.GetValue(oData, null).GetType(); <-- error
        oDataRow[oPropertyInfo.Name.ToString()] = Convert.ChangeType(oPropertyInfo.GetValue(oData, null), oType);
    }

Any help is appreciated.

GetType() is an instance method. The property value returns either an object or null . Any instance method call on a null reference will cause the error you are receiving. The GetType() method is throwing the exception when you try to call it on a null property (in your case, the Comment property).

You should instead use oPropertyInfo.PropertyType to get the property type, (which is faster anyway).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM