PropertyInfo.GetValue(myObject, null). gettype()返回“未设置为对象实例的

本文关键字:设置 对象 实例 gettype myObject GetValue null PropertyInfo 返回 | 更新日期: 2023-09-27 17:52:34

我试图将MembershipUserCollection转换为要在GridView中使用的数据集,我有这个助手类,它将通过所有成员行和属性循环并获得值和类型并将它们推入datarow。

当属性有值时,它会工作,但当属性有空值时,它会中断返回消息,"对象引用未设置为对象的实例"。

在这个特殊的例子中,当它的值为"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);
    }

PropertyInfo.GetValue(myObject, null). gettype()返回“未设置为对象实例的

GetType()是一个实例方法。属性值返回objectnull。对空引用的任何实例方法调用都将导致您正在接收的错误。当您尝试对空属性(在您的示例中是Comment属性)调用GetType()方法时,它会抛出异常。

您应该使用oPropertyInfo.PropertyType来获取属性类型,(这样更快)