我有这段代码:
string type = string.Empty;
PropertyInfo[] propertyInfos = typeof(T).GetProperties();
foreach (var item in propertyInfos)
if (item.Name.ToUpper() == searchField.ToUpper())
{
type = item.PropertyType.FullName;
break;
}
switch (type)
{
case "System.Int32":
//...
break;
case "System.Single":
//...
break;
}
代码可以工作但问题是当类型是可空的时候。怎么知道这个类型是否可以为空?可空类型(int32?long?double?)以及如何将字符串转换为此可空类型?
谢谢,
答案 0 :(得分:0)
尝试以下代码将帮助您
System.Reflection.FieldInfo[] fieldsInfos = typeof(NullWeAre).GetFields();
foreach (System.Reflection.FieldInfo fi in fieldsInfos)
{
if (fi.FieldType.IsGenericType
&& fi.FieldType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
// We are dealing with a generic type that is nullable
Console.WriteLine("Name: {0}, Type: {1}", fi.Name, Nullable.GetUnderlyingType(fi.FieldType));
}
}