问题描述
我想对get属性类型使用反射.这是我的代码
I want use reflection for get properties type.this is my code
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]]
this code propertyInfo.PropertyType.Name
is ok but if my property type is Nullable
i get this Nullable'1
string and if write FullName
if get this stirng System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
推荐答案
更改代码以查找可为空的类型,在这种情况下,将PropertyType作为第一个通用参数:
Change your code to look for nullable type, in that case take PropertyType as the first generic argument:
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));
这篇关于从Nullable类型的反射中获取PropertyType.Name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!