c# - 通过反射查找可空属性的类型

标签 c# .net reflection nullable

我通过反射检查对象的属性,并继续处理每个属性的数据类型。这是我的(简化的)来源:

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

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

最佳答案

可能的解决方案:

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

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

相关文章:

c# - 使用 ExcelDataReader 从特定单元格开始读取 Excel 数据

c# - Windows 身份验证是否使用 aspnet_Users 表?

go - 接口(interface)指针的奇怪行为

java - 尝试检索字段值时出现 NoSuchFieldException

c# - 如何在sql中将带有时区的varchar转换为datetime

c# - 如何在 C# 中的单个 SQL 查询中更新水果列表的 crate ID

.net - SQL Server 和 TransactionScope(带 MSDTC): Sporadically can't get connection

c# - 接收 : how to pass the latest value from observable into ReactiveCommand

c# - 如何记录所有抛出的异常?

C# 反射索引属性