PropertyInfo.GetValue(myObject,null).GetType()返回"未将对象引用设置为对象的实例".

Kah*_*anu 2 c# reflection properties propertyinfo

我正在尝试将MembershipUserCollection转换为要在GridView中使用的DataSet,我有这个帮助器类,它将循环遍历所有成员资格行和属性,并获取值和类型并将它们推送到DataRows.

它在有属性值时有效,但是当有一个空值时,它会中断返回消息"对象引用未设置为对象的实例.".

在这个特定的例子中,如果它的值为"null",它会在Comment字段中断.

这是我的代码:

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

任何帮助表示赞赏.

sma*_*man 7

GetType()是一个实例方法.属性值返回objectnull.对空引用的任何实例方法调用都将导致您收到的错误.GetType()当您尝试在null属性(在您的情况下,Comment属性)上调用它时,该方法抛出异常.

您应该使用oPropertyInfo.PropertyType获取属性类型(无论如何更快).