【问题标题】:Get PropertyType.Name in reflection from Nullable type从 Nullable 类型的反射中获取 PropertyType.Name
【发布时间】:2019-01-06 01:12:53
【问题描述】:

我想使用反射来获取属性类型。 这是我的代码

var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
     model.ModelProperties.Add(
                               new KeyValuePair<Type, string>
                                               (propertyInfo.PropertyType.Name,
                                                propertyInfo.Name)
                              );
}

这个代码propertyInfo.PropertyType.Name 没问题,但是如果我的属性类型是Nullable,我会得到这个Nullable'1 字符串,如果写FullName 如果得到这个搅拌System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

【问题讨论】:

  • 它是 Nullable 吗?
  • 你想得到哪个字符串?看起来您将不得不使用 PropertyType 上的属性/方法,以允许您访问该类型的通用参数。
  • this answer。它为泛型和非泛型类型创建一个可读的名称(例如System.Nullable&lt;System.Int32&gt;)。

标签: c# reflection nullable


【解决方案1】:

更改您的代码以查找可为空的类型,在这种情况下,将 PropertyType 作为第一个泛型参数:

var propertyType = propertyInfo.PropertyType;

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

model.ModelProperties.Add(new KeyValuePair<Type, string>
                        (propertyType.Name,propertyInfo.Name));

【讨论】:

    【解决方案2】:

    这是一个老问题,但我也遇到了这个问题。我喜欢@Igoy 的答案,但如果类型是可空类型的数组,它就不起作用。这是我处理可为空/泛型和数组的任何组合的扩展方法。希望对有同样问题的人有用。

    public static string GetDisplayName(this Type t)
    {
        if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
            return string.Format("{0}?", GetDisplayName(t.GetGenericArguments()[0]));
        if(t.IsGenericType)
            return string.Format("{0}<{1}>",
                                 t.Name.Remove(t.Name.IndexOf('`')), 
                                 string.Join(",",t.GetGenericArguments().Select(at => at.GetDisplayName())));
        if(t.IsArray)
            return string.Format("{0}[{1}]", 
                                 GetDisplayName(t.GetElementType()),
                                 new string(',', t.GetArrayRank()-1));
        return t.Name;
    }
    

    这将处理像这样复杂的情况:

    typeof(Dictionary<int[,,],bool?[][]>).GetDisplayName()
    

    返回:

    Dictionary<Int32[,,],Boolean?[][]>
    

    【讨论】:

      猜你喜欢
      • 2012-01-22
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 2012-04-03
      • 2015-09-13
      • 1970-01-01
      相关资源
      最近更新 更多