从Nullable类型的反射中获取PropertyType.Name我想使用反射获取属性类型。这是我的代码varproperties=type.GetProperties();foreach(varpropertyInfoinproperties){model.ModelProperties.Add(newKeyValuePair(propertyInfo.PropertyType.Name,propertyInfo.Name));这段代码propertyInfo.PropertyType.Name,但是如果我的属性类型是Nullable我得到这个Nullable'1字符串,如果我得到名字,我可以写FullNameSystem.Nullable1[[System.DateTime,mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089]]更改您的代码以查找可空类型,在本例中PropertyType作为第一个通用协议:varpropertyType=propertyInfo.PropertyType;如果(propertyType.IsGenericType&&propertyType.GetGenericTypeDefinition()==typeof(Nullable)){propertyType=propertyType.GetGenericArguments()[0];}model.ModelProperties.Add(newKeyValuePair(propertyType.Name,propertyInfo.Name));这是一个老问题,但我也遇到了。我喜欢@Igoy的回答,但如果类型是可空类型的数组,它就不起作用。这是我的扩展方法,它处理可空/泛型和数组的任意组合。希望它对有同样问题的人有用。publicstaticstringGetDisplayName(thisTypet){if(t.IsGenericType&&t.GetGenericTypeDefinition()==typeof(Nullable))returnstring.Format("{0}?",GetDisplayName(t.GetGenericArguments()[0]));if(t.IsGenericType)返回string.Format("{0}",t.Name.Remove(t.Name.IndexOf('`')),string.Join(",",t.GetGenericArguments().Select(at=>at.GetDisplayName())));if(t.IsArray)返回string.Format("{0}[{1}]",GetDisplayName(t.GetElementType()),newstring(',',t.GetArrayRank()-1));返回t.Name;这将处理以下复杂情况:typeof(Dictionary).GetDisplayName()返回:以上是C#学习教程:从Nullable类型中获取反射的所有PropertyType.Name共享的内容,如果对你有用,你需要想了解更多C#学习教程,希望大家多加关注——词典本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
