C# 如何检查两个值之一是否为 TRUE?

发布于 2024-09-14 19:26:26 字数 231 浏览 6 评论 0原文

对于 C# 专家来说这应该是一个简单的问题。

我基本上想检查一个值或另一个值是否为 TRUE,代码如下:

if ((Boolean.Parse(staff.getValue("Male")) | Boolean.Parse(staff.getValue("Female")))    
{   
   // is true
}

这是正确的吗?

谢谢

Should be a simple question for the C# experts here.

I basically want to check if one value or another is TRUE, a wild stab at the code is below:

if ((Boolean.Parse(staff.getValue("Male")) | Boolean.Parse(staff.getValue("Female")))    
{   
   // is true
}

Is this correct?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

真心难拥有 2024-09-21 19:26:26

如果“恰好有一个”为真,那么它就是:

var male = bool.Parse(staff.getValue("Male"));
var female = bool.Parse(staff.getValue("Female"));

if (male ^ female)    
{
   //is true
}

If EXACTLY ONE should be true then it is:

var male = bool.Parse(staff.getValue("Male"));
var female = bool.Parse(staff.getValue("Female"));

if (male ^ female)    
{
   //is true
}
左耳近心 2024-09-21 19:26:26

听起来您正在寻找逻辑“或”。

if(condition1 || condition2)
{
}

Sounds like you're looking for the logical OR.

if(condition1 || condition2)
{
}
裸钻 2024-09-21 19:26:26

使用||(双管道)、逻辑或。

bool isMale = Boolean.Parse(staff.getValue("Male");
bool isFemale = Boolean.Parse(staff.getValue("Female");
if (isMale || isFemale) // note double pipe ||
{
   // do something if true
}

在 C# 语句表达式中,从左到右求值。在 OR 运算中,如果第一个表达式等于 true,则不会计算第二个表达式。

Use the || (double pipe), logical OR.

bool isMale = Boolean.Parse(staff.getValue("Male");
bool isFemale = Boolean.Parse(staff.getValue("Female");
if (isMale || isFemale) // note double pipe ||
{
   // do something if true
}

In C# statement expressions are evaluated from left to right. In an OR operation, the second expression will not be evaluated if the first one equals true.

胡大本事 2024-09-21 19:26:26

条件 OR 运算符 || 就是您所需要的

if ((Boolean.Parse(staff.getValue("Male")) || Boolean.Parse(staff.getValue("Female")))
{
   //is true
}

如果第一个条件为 TRUE,则不会检查第二个条件,因为结果显然将返回 正确。

The conditional OR operator || is what you need

if ((Boolean.Parse(staff.getValue("Male")) || Boolean.Parse(staff.getValue("Female")))
{
   //is true
}

If the first condition is TRUE, then the second condition isn't checked since the outcome is obviously going to return TRUE.

银河中√捞星星 2024-09-21 19:26:26

请注意,TryParseParse 工作得更快、更安全,因为在发生错误时不会引发异常。 TryParse 返回布尔值,指示解析是否成功。

因此,两种解析方法都应返回 true 并且仅在此之后 - 进行主要检查

bool male, female;
if ((Boolean.TryParse(staff.getValue("Male"), out male) && 
     Boolean.TryParse(staff.getValue("Female"), out female)) &&
    (male || female)) // or ^
{
    // do stuff
}

bool male, female;
if (Boolean.TryParse(staff.getValue("Male"), out male) &&
     Boolean.TryParse(staff.getValue("Female"), out female))        
{
    if(male) { }
    else if (female) { } // or just else
}
else
{
     // staff contains wrong data. Probably "yeap" instead of "true"
}

Note that TryParse works more fast and more safe then just Parse because doesn't throw an exception in case of error. TryParse returns bool that indicates was parse successful or was not.

So both parsing methods should return true and only after that - do the main check

bool male, female;
if ((Boolean.TryParse(staff.getValue("Male"), out male) && 
     Boolean.TryParse(staff.getValue("Female"), out female)) &&
    (male || female)) // or ^
{
    // do stuff
}

or

bool male, female;
if (Boolean.TryParse(staff.getValue("Male"), out male) &&
     Boolean.TryParse(staff.getValue("Female"), out female))        
{
    if(male) { }
    else if (female) { } // or just else
}
else
{
     // staff contains wrong data. Probably "yeap" instead of "true"
}
幼儿园老大 2024-09-21 19:26:26

要指示性别是否使用“true”值而不是“false”指定,

bool genderIsSpecified = staff.getValue("Male") | staff.getValue("Female");

.. 将仅确定它是否是这些值之一,而不是对象 staff 是这些值中的哪一个。

所以,以防万一这个问题是字面意义而不是抽象的例子,……

男性或女性……每个人都是其中之一。也许在你的问题中你想问的是这两种情况中的哪一种?在这种情况下,

bool defaultGenderIfNoGenderDocumented = true; // male
bool MaleIfTrue_FemaleIfFalse = !string.IsNullOrEmpty(staff.getValue("Male"))
    ? bool.Parse(staff.getValue("Male"))
    : string.IsNullOrEmpty(staff.getValue("Female"))
        ? bool.Parse(staff.getValue("Female"))
            ? false
            : defaultGenderIfNoGenderDocumented
        : defaultGenderIfNoGenderDocumented;

或者简单地说,

// assume value is properly populated, ignore "Female" value
bool isMale = bool.Parse(staff.getValue("Male")); 

To indicate whether a gender is specified with a value of "true" rather than "false",

bool genderIsSpecified = staff.getValue("Male") | staff.getValue("Female");

.. will only determine whether it's one of those values, not which of those values the object staff is.

So, just in case this question is literal and not an abstract example, ...

Male or Female .. everyone is one or the other. Perhaps in your question you meant to ask which of the two is the case? In that case,

bool defaultGenderIfNoGenderDocumented = true; // male
bool MaleIfTrue_FemaleIfFalse = !string.IsNullOrEmpty(staff.getValue("Male"))
    ? bool.Parse(staff.getValue("Male"))
    : string.IsNullOrEmpty(staff.getValue("Female"))
        ? bool.Parse(staff.getValue("Female"))
            ? false
            : defaultGenderIfNoGenderDocumented
        : defaultGenderIfNoGenderDocumented;

Or simply,

// assume value is properly populated, ignore "Female" value
bool isMale = bool.Parse(staff.getValue("Male")); 
将军与妓 2024-09-21 19:26:26

这是一个类似的场景,但我正在检查三个或更多布尔值。

Thread th = new Thread(() =>
                {
                    while (true)
                    {
                        bool allReadComplete = true;

                        foreach (IDataProvider provider in lstDataProviders)
                        {
                            provider.StartReading();

                            if (provider.FinishedReading)
                              allReadComplete = allReadComplete && provider.FinishedReading;
                            else
                              allReadComplete = provider.FinishedReading;
                        }

                        // to induce some context switching
                        Thread.Sleep(0);

                        if (allReadComplete)
                            break;
                    }

                    Console.WriteLine("Thread Exiting");

                });
            th.IsBackground = true;
            th.Start();

This is a similar scenario but I am checking for three or more bool values.

Thread th = new Thread(() =>
                {
                    while (true)
                    {
                        bool allReadComplete = true;

                        foreach (IDataProvider provider in lstDataProviders)
                        {
                            provider.StartReading();

                            if (provider.FinishedReading)
                              allReadComplete = allReadComplete && provider.FinishedReading;
                            else
                              allReadComplete = provider.FinishedReading;
                        }

                        // to induce some context switching
                        Thread.Sleep(0);

                        if (allReadComplete)
                            break;
                    }

                    Console.WriteLine("Thread Exiting");

                });
            th.IsBackground = true;
            th.Start();
如歌彻婉言 2024-09-21 19:26:26

无论如何,需要进行一些异常检查。 Boolean.Parse() 方法获取一个字符串作为参数,并仅返回 truefalse 如果参数一旦去掉空格就等于“True”或“False”(注意大小写)。在任何其他情况下,该函数都会返回异常。

假设 staff.getValue("Male")staff.getValue("Female") 的可能值正是这两个,那么简单的析取 (||) 就足够了。如果可能有任何其他返回值,包括null和空字符串,那么您必须检查异常

bool isMale;
try {
    isMale = Boolean.Parse(staff.getValue("Male"));
} catch(Exception e) {
    isMale = Boolean.False;
}
try {
    isFemale = Boolean.Parse(staff.getValue("Female"));
} catch(Exception e) {
    isFemale = Boolean.False;
}
if (isMale || isFemale) // note double pipe ||
{
    // do something if true
}

或手动比较

bool isMale = Boolean.TrueValue == staff.getValue("Male");
bool isFemale = Boolean.TrueValue == staff.getValue("Female");
if (isMale || isFemale) // note double pipe ||
{
    // do something if true
}

A little exception checking is needed anyway. The Boolean.Parse() method gets a string as argument and returns either true or false only if the argument, once stripped out of whitespace, is equal to "True" or "False" (note capitalization). In ANY other case the function returns an exception.

Supposing that the possible values of staff.getValue("Male") and staff.getValue("Female") are exactly those two, then the simple disjunction (||) is sufficient. If any other return value is possible, including null and the empty string, then you have to check for exceptions

bool isMale;
try {
    isMale = Boolean.Parse(staff.getValue("Male"));
} catch(Exception e) {
    isMale = Boolean.False;
}
try {
    isFemale = Boolean.Parse(staff.getValue("Female"));
} catch(Exception e) {
    isFemale = Boolean.False;
}
if (isMale || isFemale) // note double pipe ||
{
    // do something if true
}

or compare manually

bool isMale = Boolean.TrueValue == staff.getValue("Male");
bool isFemale = Boolean.TrueValue == staff.getValue("Female");
if (isMale || isFemale) // note double pipe ||
{
    // do something if true
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文