简体   繁体   English

string.IsNullOrEmpty() 与 string.NotNullOrEmpty()

[英]string.IsNullOrEmpty() vs string.NotNullOrEmpty()

I'm curious if any developers use string.IsNullOrEmpty() more often with a negative than with a positive我很好奇是否有任何开发人员使用 string.IsNullOrEmpty() 更频繁地使用负数而不是正数

eg例如

if (!string.IsNullOrEmpty())

This is how I use the method 99% of the time.这就是我 99% 的时间使用该方法的方式。 What was the design decision for this?对此的设计决策是什么?

Because "IsNullOrEmpty" is easier to understand than "NotNullOrEmpty".因为“IsNullOrEmpty”比“NotNullOrEmpty”更容易理解。 The latter could be interpreted as:后者可以解释为:

  1. It's not null and it's not empty它不是空的,也不是空的
  2. It's not null or it is empty它不为空或为空

Double negatives are usually discouraged in naming stuff.在命名东西时通常不鼓励双重否定。 !string.NotNullOrEmpty(...) would make one. !string.NotNullOrEmpty(...)会生成一个。

For those logicians out there, !string.IsNullOrEmpty is not equivalent to string.IsNotNullOrEmpty.对于那些逻辑学家来说,!string.IsNullOrEmpty 不等同于 string.IsNotNullOrEmpty。 @Guffa has it correct. @Guffa 说得对。 Using DeMorgan's law, it would have to be string.IsNotNullAndNotEmpty to be equivalent.使用德摩根定律,它必须是 string.IsNotNullAndNotEmpty 才能等效。

¬(null ∨ empty) ⇔ ¬null ∧ ¬empty ¬(null ∨ 空) ⇔ ¬null ∧ ¬空

¬(null ∨ empty) ≠ ¬null ∨ empty ¬(null ∨ 空) ≠ ¬null ∨ 空

The point here, I guess, is that the way it is currently is unambiguous, where as making the opposite unambiguous would be cumbersome.我想这里的重点是它目前的方式是明确的,而让相反的方式明确会很麻烦。

C# naming conventions dictate that your expressions should be in the positive such as "Is..." and not "IsNot..." C# 命名约定规定您的表达式应该是正数,例如“Is...”而不是“IsNot...”

EDIT: Typically, I use it when doing error checking and input validation at the beginning of a method and raise an exception if the parameter is null or empty.编辑:通常,我在方法开始时进行错误检查和输入验证时使用它,如果参数为 null 或为空,则会引发异常。

if (string.IsNullOrEmpty(myParameter))
{
throw new ....
}

I prefer the extension method:我更喜欢扩展方法:

public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string value)
    {
        return string.IsNullOrEmpty(value);
    }
}

I find it reads better to say:我觉得这样说更好看:

if(myValue.IsNullOrEmpty())

or要么

if(!myValue.IsNullOrEmpty())

I always create an extension method for "HasContent()" which generally makes sense, follows the "positive" specifications, and saves on code bloat because I use it much more often than its counterpart:我总是为“HasContent()”创建一个扩展方法,它通常是有意义的,遵循“积极”规范,并节省代码膨胀,因为我比它的对应物更频繁地使用它:

public static bool HasContent(this string s) {
    return !string.IsNullOrEmpty(s);
}

也许是因为那样名称必须是冗长的IsNotNullAndNotEmpty才能如此具体。

当然,您现在可以始终使用string.IsNullOrWhiteSpace(string)而不是 .NET 4.0 中的string .IsNullOrEmpty(string)

I would actually be inclined to offer a different answer from the "it's ambiguous" explanation provided by several others (though I agree with that answer as well):我实际上倾向于提供与其他几个人提供的“这是模棱两可的”解释不同的答案(尽管我也同意该答案):

Personally, I like to minimize nesting in my code, as (to me) the more curly braces code has, the harder it becomes to follow.就我个人而言,我喜欢尽量减少代码中的嵌套,因为(对我而言)代码中花括号越多,就越难遵循。

Therefore I'd much prefer this (for example):因此我更喜欢这个(例如):

public bool DoSomethingWithString(string s) {
    if (string.IsNullOrEmpty(s))
        return false;

    // here's the important code, not nested
}

to this:对此:

public bool DoSomethingWithString(string s) {
    if (!string.IsNullOrEmpty(s)) {
        // here's the important code, nested
    } else {
        return false;
    }
}

This is a pretty specific scenario (where a null/empty string prompts an immediate exit) and clearly isn't the way a method using IsNullOrEmpty would always be structured;这是一个非常具体的场景(空/空字符串提示立即退出)并且显然不是使用IsNullOrEmpty的方法总是结构化的方式; but I think it's actually pretty common.但我认为这实际上很常见。

这是我见过的最常见的用法。

"NotNullOrEmpty" is ambiguous, it could mean "(not null) or empty" or it could mean "not (null or empty)". “NotNullOrEmpty”是不明确的,它可能意味着“(非空)或空”,也可能意味着“非(空或空)”。 To make it unambiguous you'd have to use "NotNullAndNotEmpty", which is a mouthfull.为了使它明确,你必须使用“NotNullAndNotEmpty”,这是一个满口的。

Also, the "IsNullOrEmpty" naming encourages use as a guard clause, which I think is useful.此外,“IsNullOrEmpty”命名鼓励用作保护子句,我认为这很有用。 Eg:例如:

if (String.IsNullOrEmpty(someString))
{
   // error handling
   return;
}
// do stuff

which I think is generally cleaner than:我认为这通常比以下内容更清洁:

if (!String.IsNullOrEmpty(someString))
{
   // do stuff
}
else
{
   // error handling
   return;
}

I had the same question before I realized all I had to do to flip the question was to put the Not operator in front of the conditional.在我意识到翻转问题所需要做的就是将 Not 运算符放在条件之前,我遇到了同样的问题。 I think it cleande up my code some.我认为它清理了我的代码。

 // need to check if tBx_PTNum.Text is empty
        /*
        if (string.IsNullOrWhiteSpace(tBx_PTNum.Text))
        {
            // no pt number yet
        }
        else
        {
            ptNum = Convert.ToInt32(tBx_PTNum.Text);
        }
        */
        
        if(!string.IsNullOrEmpty(tBx_PTNum.Text))
        {
            ptNum = Convert.ToInt32(tBx_PTNum.Text);
        }

Personally I prefer to cater for the non negated scenario first.就我个人而言,我更喜欢首先满足非否定的情况。 It just makes sense to me to do the true part first and then the false.对我来说,先做真实的部分,然后做虚假的部分才有意义。 Comes down to personal style.归结为个人风格。

I've always thought it seemed the wrong way round as I use the negative much more often than the positive.我一直认为这似乎是错误的方式,因为我使用否定词的频率比肯定词要多得多。

I would also like there to be an instance IsEmpty() or IsNotEmpty() for use when the variable is declared within the function.我还希望有一个实例 IsEmpty() 或 IsNotEmpty() 用于在函数中声明变量时使用。 This could not be IsNullOrEmpty() or IsNotNullOrEmpty() as if the instance was null then you would get a null reference exception.这不能是 IsNullOrEmpty() 或 IsNotNullOrEmpty(),就像实例为空一样,那么您将获得空引用异常。

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

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