首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >通过反射查找可为空的属性的类型

通过反射查找可为空的属性的类型
EN

Stack Overflow用户
提问于 2011-04-13 12:54:33
回答 6查看 50.7K关注 0票数 88

我通过反射检查对象的属性,并继续处理每个属性的数据类型。以下是我的(精简)源代码:

代码语言:javascript
复制
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;
  }
}

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

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-04-13 12:58:19

可能的解决方案:

代码语言:javascript
复制
    propertyType = propertyInfo[propertyInfoIndex].PropertyType;
    if (propertyType.IsGenericType &&
        propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
      propertyType = propertyType.GetGenericArguments()[0];
    }
票数 141
EN

Stack Overflow用户

发布于 2011-04-13 13:03:59

Nullable.GetUnderlyingType(fi.FieldType)将为你做这些工作,检查下面的代码来做你想做的事情

代码语言:javascript
复制
System.Reflection.FieldInfo[] fieldsInfos = typeof(NullWeAre).GetFields();

        foreach (System.Reflection.FieldInfo fi in fieldsInfos)
        {
            if (fi.FieldType.IsGenericType
                && fi.FieldType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                // We are dealing with a generic type that is nullable
                Console.WriteLine("Name: {0}, Type: {1}", fi.Name, Nullable.GetUnderlyingType(fi.FieldType));
            }

    }
票数 37
EN

Stack Overflow用户

发布于 2013-07-11 17:23:53

代码语言:javascript
复制
foreach (var info in typeof(T).GetProperties())
{
  var type = info.PropertyType;
  var underlyingType = Nullable.GetUnderlyingType(type);
  var returnType = underlyingType ?? type;
}
票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5644587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档