簡體   English   中英

如何將數字字符串對象轉換為可為空的數字

[英]How to convert numeric string object to nullable numeric

在下面的示例中,對ConvertNumericStringObj進行了兩次調用,兩次都發送回Type int對象。

string strValue = "123";
object obj = ConvertNumericStringObj(typeof(int), strValue);
object obj = ConvertNumericStringObj(typeof(int?), strValue);   

public static object ConvertNumericStringObj(Type conversion, object value)
{
    var t = conversion;
    if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
        if (value == null)
        {
            return null;
        }
        t = Nullable.GetUnderlyingType(t);
    }
    return Convert.ChangeType(value, t);
}

我的問題是:是否有某種方式可以傳遞字符串和int? 輸入並轉換它,以便它返回一個int? 賓語?

如果你想類型可能是要么 intint? ,那么您正在尋找的是“泛型”。 這應該給您您想要的。

public static T ConvertNumericStringObj<T>(string value)
{
    var t = typeof (T);
    if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
        if (string.isNullOrEmpty(value))
            return default(T);

        t = Nullable.GetUnderlyingType(t);
    }
    return (T)Convert.ChangeType(value, t);
}

但是 ,我很好奇您為什么不只返回int.TryParse()生成的可為空的整數。

public static int? ConvertNumericStringObj(string value)
{
    int? x;

    if (int.TryParse(value , out x)
        return x;

    return null;
}

是的你可以。 試試Int32.TryParse

public static int? ConvertNumericStringObj(string strValue)
{
    int x;
    if (Int32.TryParse(strValue , out x)
        return x;
    return null;
}

但我想知道,是否一定需要傳遞int?

編輯:由於OP要求它有點通用,請嘗試擴展方法(大致),例如:

public static T? ConvertNumericStringObj<T>(string strValue) 
{
    if (string.IsNullOrEmpty(strValue))
        return null;
    return (T) Convert.ChangeType(strValue, typeof(T));
}

這樣,您可以將其用作:

詮釋? x = strX.ConvertNumericStringObj();

暫無
暫無

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

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