我通过反射检查对象的属性,然后继续处理每个属性的数据类型。这是我的(精简版)资源:

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;
  }
}

我的问题是,我新需要处理可为空的属性,但是我不知道如何获取可为空的属性的类型。

最佳答案

可能的解决方案:

    propertyType = propertyInfo[propertyInfoIndex].PropertyType;
    if (propertyType.IsGenericType &&
        propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
      propertyType = propertyType.GetGenericArguments()[0];
    }

关于c# - 通过反射查找可为空的属性的类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5644587/

10-09 02:51