从Nullable类型获取反射中的PropertyType.Name

10 c# reflection nullable

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

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

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

Igo*_*goy 24

更改代码以查找可空类型,在这种情况下,将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));
Run Code Online (Sandbox Code Playgroud)


Joe*_*een 10

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

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;
}
Run Code Online (Sandbox Code Playgroud)

这将处理如下复杂的案例:

typeof(Dictionary<int[,,],bool?[][]>).GetDisplayName()
Run Code Online (Sandbox Code Playgroud)

返回:

Dictionary<Int32[,,],Boolean?[][]>
Run Code Online (Sandbox Code Playgroud)