[英]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. 我正在尝试将MembershipUserCollection转换为要在GridView中使用的DataSet,并且我有这个帮助器类,该类将遍历所有成员资格行和属性,并获取值和类型并将其推入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". 在此特定示例中,如果其值为“ null”,则它将在Comment字段上中断。
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. GetType()
是一个实例方法。 The property value returns either an object
or null
. 该属性值返回一个object
或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). 当您尝试在null属性(在您的情况下为Comment属性)上调用GetType()
方法时,将GetType()
异常。
You should instead use oPropertyInfo.PropertyType
to get the property type, (which is faster anyway). 相反,您应该使用oPropertyInfo.PropertyType
来获取属性类型(无论如何这都会更快)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.