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

use*_*274 76 .net c# 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*kus 120

解决方案:

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

  • **可以在一行中完成!**:`propertyType = Nullable.GetUnderlyingType(propertyType)?? propertyType` (69认同)
  • 确实在`propertyType.GetGenericTypeDefinition()`之前需要`propertyType.IsGenericType`,否则抛出异常.+1 (6认同)
  • MSDN上也提到了对Nullables的正确检查:http://msdn.microsoft.com/en-us/library/ms366789.aspx。如果需要,您可以在此处找到有关该主题的更多资源。 (2认同)

Pra*_*ana 36

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

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

    }
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢`Nullable.GetUnderlyingType(type)`解决方案,因为它比`type.GetGenericArguments()[0]`更明确,至少在这种情况下. (5认同)
  • 你**不需要检查IsGenericType和GetGenericTypeDefinition**,`Nullable.GetUnderlyingType`已经在本地执行.当类型不是Nullable <>时,GetUnderlyingType返回null(来源:http://msdn.microsoft.com/en-US/library/system.nullable.getunderlyingtype(v=vs.110).aspx) (5认同)

Min*_*ang 14

foreach (var info in typeof(T).GetProperties())
{
  var type = info.PropertyType;
  var underlyingType = Nullable.GetUnderlyingType(type);
  var returnType = underlyingType ?? type;
}
Run Code Online (Sandbox Code Playgroud)


Ami*_*mir 6

正如Yves M.所指出的, 它很简单,如下所示。

var properties = typeof(T).GetProperties();

  foreach (var prop in properties)
  {
     var propType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
     var dataType = propType.Name;
  }
Run Code Online (Sandbox Code Playgroud)