从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()
返回:
上述就是C#学习教程:从Nullable类型获取reflection中的PropertyType.Name分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
Dictionary
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1026782.html