簡體   English   中英

如何檢測與可為空屬性相結合的數據類型

[英]How to detect data type combined with nullable property

我使用反射來檢索泛型類對象屬性,通過檢測它們的數據類型(例如 System.String、System.DateTime 等)並根據數據類型轉換值,例如:

switch (prop.PropertyType.FullName)
{
    case "System.String":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            string.Empty : Convert.ToString(_propertyDataValue));
        break;
    case "System.Int32":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            -1 : Convert.ToInt32(_propertyDataValue));
        break;
    case "System.DateTime":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            DateTime.MinValue : Convert.ToDateTime(_propertyDataValue));
        break;
    case "System.Double":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            0 : Convert.ToDouble(_propertyDataValue));
        break;
    case "System.Boolean":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            false : Convert.ToBoolean(_propertyDataValue));
        break;
    default:
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            string.Empty : Convert.ToString(_propertyDataValue));
        break;
}

但是,當我遇到定義為int?的屬性時,double? 或日期時間? 這將是一個 Nullable 類型,我無法確定該屬性的確切數據類型,反射只給我類型為 "System.Nullable" ,無論如何檢測后面的組合數據類型?

正如@madreflection在評論部分提到的那樣。 您需要使用Nullable.GetUnderlyingType如下:

var propType = prop.PropertyType;

if (Nullable.GetUnderlyingType(propType) != null)
{
    // It's nullable
    propType = Nullable.GetUnderlyingType(propType);
}

switch (propType.FullName)
{
    case "System.String":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            string.Empty : Convert.ToString(_propertyDataValue));
        break;
    case "System.Int32":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            -1 : Convert.ToInt32(_propertyDataValue));
        break;
    case "System.DateTime":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            DateTime.MinValue : Convert.ToDateTime(_propertyDataValue));
        break;
    case "System.Double":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            0 : Convert.ToDouble(_propertyDataValue));
        break;
    case "System.Boolean":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            false : Convert.ToBoolean(_propertyDataValue));
        break;
    default:
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            string.Empty : Convert.ToString(_propertyDataValue));
        break;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM