Convert.ChangeType from int to bool

本文关键字:to bool int from ChangeType Convert | 更新日期: 2023-09-27 18:33:58

使用以下命令从查询字符串中获取值,并在需要时转换为特定类型。

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);

但是,当尝试执行以下操作时,它无法正常工作,所以我的问题是,如果从查询字符串变量中检索的值是 1 或 0 而不是 true 的 false,是否可以更改代码以处理布尔值。

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.ChangeType from int to bool

您可以修改转换方法以处理布尔值,如下所示:

//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"