簡體   English   中英

Convert.ChangeType從int轉換為bool

[英]Convert.ChangeType from int to bool

需要使用以下內容從查詢字符串獲取值並將其轉換為特定類型。

public static T Convert<T>(NameValueCollection QueryString, string KeyName, T DefaultValue) where T : IConvertible
    {
        //Get the attribute
        string KeyValue = QueryString[KeyName];

        //Not exists?
        if (KeyValue == null) return DefaultValue;

        //Empty?
        if (KeyValue == "") return DefaultValue;

        //Convert
        try
        {
            return (T)System.Convert.ChangeType(KeyValue, typeof(T));
        }
        catch
        {
            return DefaultValue;
        }
    } 

這樣會打電話

int var1 = Convert<int>(HttpContext.Current.Request.QueryString,"ID", 0);

但是,當嘗試執行以下操作時,它不能正常工作,所以我的問題是,如果從querystring變量中檢索的值是1或0,而不是true,則可以更改代碼以處理bool。

ie... instead of
http://localhost/default.aspx?IncludeSubs=true
the call is
http://localhost/default.aspx?IncludeSubs=1

bool var1 = Convert<bool>(HttpContext.Current.Request.QueryString,"IncludeSubs", false);

您可以按以下方式修改您的convert方法以處理布爾值:

//Convert
try
{
    var type = typeof(T);
    if(type == typeof(bool))
    {
        bool boolValue;
        if(bool.TryParse(KeyValue, out boolValue))
            return boolValue;
        else
        {
            int intValue;
            if(int.TryParse(KeyValue, out intValue))
                return System.Convert.ChangeType(intValue, type);
        }
    }
    else
    {
        return (T)System.Convert.ChangeType(KeyValue, type);
    }
}
catch
{
    return DefaultValue;
}

這樣,您可以轉換為布爾值,例如: "true""False""0""1"

暫無
暫無

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

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