简体   繁体   English

Convert.ChangeType从int转换为bool

[英]Convert.ChangeType from int to bool

Using the following to get values from query string and convert to specific types should there be a need. 需要使用以下内容从查询字符串获取值并将其转换为特定类型。

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

A call would be made as such 这样会打电话

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

However when trying to do the following it does not work correctly so my question is, is it possible to change the code to handle bools if the value being retrieved from the querystring variable is a 1 or a 0 instead of a true of false. 但是,当尝试执行以下操作时,它不能正常工作,所以我的问题是,如果从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);

You can modify your convert method in order to handle booleans as following: 您可以按以下方式修改您的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;
}

In this way you can convert to boolean values like: "true" , "False" , "0" , "1" 这样,您可以转换为布尔值,例如: "true""False""0""1"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM