通过反射查找可为空属性的类型
我通过反射检查对象的属性,并继续处理每个属性的数据类型。这是我的(减少的)来源:
private void ExamineObject(object o)
{
Type type = default(Type);
Type propertyType = default(Type);
PropertyInfo[] propertyInfo = null;
type = o.GetType();
propertyInfo = type.GetProperties(BindingFlags.GetProperty |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance);
// Loop over all properties
for (int propertyInfoIndex = 0; propertyInfoIndex <= propertyInfo.Length - 1; propertyInfoIndex++)
{
propertyType = propertyInfo[propertyInfoIndex].PropertyType;
}
}
我的问题是,我新需要处理可为空的属性,但我不知道如何获取可为空的属性的类型。
I examine the properties of an object via reflection and continue processing the data type of each property. Here is my (reduced) source:
private void ExamineObject(object o)
{
Type type = default(Type);
Type propertyType = default(Type);
PropertyInfo[] propertyInfo = null;
type = o.GetType();
propertyInfo = type.GetProperties(BindingFlags.GetProperty |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance);
// Loop over all properties
for (int propertyInfoIndex = 0; propertyInfoIndex <= propertyInfo.Length - 1; propertyInfoIndex++)
{
propertyType = propertyInfo[propertyInfoIndex].PropertyType;
}
}
My problem is, that I newly need to handle nullable properties, but I have no clue how to get the type of a nullable property.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
可能的解决方案:
possible solution:
Nullable.GetUnderlyingType(fi.FieldType)
将为您完成工作,检查下面的代码以完成您想要的操作Nullable.GetUnderlyingType(fi.FieldType)
will do the work for you check below code for do the thing you want正如 Yves M. 所指出的,它很简单,如下所示。
As pointed out by Yves M. it is as simple as below.
我正在使用循环来遍历所有类属性以获取属性类型。我使用以下代码:
I am using a loop to go through all class properties to get the property type. I use the following code:
此方法简单、快速、安全
This method is easy, fast and safe