TryParse在C#中的应用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/180658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:52:35  来源:igfitidea点击:

Application of TryParse in C#

c#

提问by

When 'val' below is not a boolI get an exception, I believe I can use TryParsebut I'm not sure how best to use it with my code below. Can anyone help?

当下面的 'val' 不是一个bool例外时,我相信我可以使用,TryParse但我不确定如何最好地将它与下面的代码一起使用。任何人都可以帮忙吗?

checkBox.Checked = Convert.ToBoolean(val);

Thanks

谢谢

回答by Greg Beech

The code is as follows to determine whether the string valis a valid Boolean value and use it to set the Checkedproperty if so. You need to decide what action you would take if it does not represent a valid value.

代码如下判断字符串val是否为有效的布尔值,Checked如果是,则使用它来设置属性。如果它不代表有效值,您需要决定要采取什么行动。

bool result;
if (bool.TryParse(val, out result))
{
    // val does represent a Boolean
    checkBox.Checked = result;
}
else
{
    // val does not represent a Boolean
}

回答by John Sheehan

Assuming that if its not a valid boolean, you don't want it checked:

假设如果它不是一个有效的布尔值,你不希望它被检查:

bool result = false;
bool.TryParse(val, out result);
checkBox.Checked = result;

回答by Yes - that Jake.

bool z = false;
if(Boolean.TryParse(val, out z))
{
  checkBox.Checked = z;
}

Just a note: Parse and convert are different operations and may lead to different results.

请注意:解析和转换是不同的操作,可能会导致不同的结果。

回答by Mesh

bool isBool = false;

bool isBool = false;

bool.TryParse( val, ref isBool );

bool.TryParse( val, ref isBool );

if( isBool )    
{
   ///ok;

}
else
{
  // fail;
}

回答by ljs

Well it depends; if you want checkBox.Checked to be equal to true if val - if it is a string - parses to true then use the following:-

这要看情况; 如果您希望 checkBox.Checked 等于 true if val - 如果它是一个字符串 - 解析为 true 然后使用以下内容:-

bool output;
checkBox.Checked = bool.TryParse(val, out output) && output;

If bool is not a string then you need to decide how to deal with it depending on its type, e.g.:-

如果 bool 不是字符串,则您需要根据其类型决定如何处理它,例如:-

checkBox.Checked = val != 0; 

etc.

等等。

回答by pezi_pink_squirrel

Good answers here already.

这里已经有了很好的答案。

I will however add, do be careful with TryParse, because contrary to what its name indicates, it can infact still throw an ArgumentException!

但是,我要补充一点,使用 TryParse 时要小心,因为与其名称所指示的相反,它实际上仍然会抛出 ArgumentException!

That's one of my pet annoyances with .NET! :)

这是我对 .NET 的最大烦恼之一!:)

回答by mkamoski

FWIW, the following may also come in handy in this (or similar) cases...

FWIW,在这种(或类似)情况下,以下内容也可能派上用场......

bool myBool = val ?? false;

...which is the good old "null-coalescing operator" and quite nice.

...这是旧的“空合并运算符”,非常好。

Read more about it here if you are interested: http://msdn.microsoft.com/en-us/library/ms173224.aspx

如果您有兴趣,请在此处阅读更多相关信息:http: //msdn.microsoft.com/en-us/library/ms173224.aspx

回答by Mick Bruno

Just posted this same snippet for another question, but here is the code I use across projects for doing a much better job of handling booleans in all their assorted versions:

刚刚为另一个问题发布了相同的代码段,但这里是我跨项目使用的代码,以便更好地处理所有各种版本的布尔值:

bool shouldCheck;
TryParseBool(val, out shouldCheck);
checkBox.Checked = shouldCheck;

/// <summary>
/// Legal values: Case insensitive strings TRUE/FALSE, T/F, YES/NO, Y/N, numbers (0 => false, non-zero => true)
/// Similar to "bool.TryParse(string text, out bool)" except that it handles values other than 'true'/'false'
/// </summary>
public static bool TryParseBool(object inVal, out bool retVal)
{
    // There are a couple of built-in ways to convert values to boolean, but unfortunately they skip things like YES/NO, 1/0, T/F
    //bool.TryParse(string, out bool retVal) (.NET 4.0 Only); Convert.ToBoolean(object) (requires try/catch)
    inVal = (inVal ?? "").ToString().Trim().ToUpper();
    switch ((string)inVal)
    {
        case "TRUE":
        case "T":
        case "YES":
        case "Y":
            retVal = true;
            return true;
        case "FALSE":
        case "F":
        case "NO":
        case "N":
            retVal = false;
            return true;
        default:
            // If value can be parsed as a number, 0==false, non-zero==true (old C/C++ usage)
            double number;
            if (double.TryParse((string)inVal, out number))
            {
                retVal = (number != 0);
                return true;
            }
            // If not a valid value for conversion, return false (not parsed)
            retVal = false;
            return false;
    }
}