如何通过反射知道可空类型

时间:2012-12-18 07:19:49

标签: c# .net reflection

  

可能重复:
  Detecting a Nullable Type via reflection

我有这段代码:

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?)以及如何将字符串转换为此可空类型?

谢谢,

1 个答案:

答案 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));
            }

    }