从Nullable类型获取reflection中的PropertyType.Name

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

var properties = type.GetProperties(); foreach (var propertyInfo in properties) { model.ModelProperties.Add( new KeyValuePair (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]]

更改代码以查找可空类型,在这种情况下,将PropertyType作为第一个通用agruement:

 var propertyType = propertyInfo.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { propertyType = propertyType.GetGenericArguments()[0]; } model.ModelProperties.Add(new KeyValuePair (propertyType.Name,propertyInfo.Name)); 

这是一个老问题,但我也遇到了这个问题。 我喜欢@ 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; } 

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

 typeof(Dictionary).GetDisplayName() 

返回:

 Dictionary