C尖锐概念中的StringIsNullOrEmpty [英] StringIsNullOrEmpty in C sharp concept

查看:104
本文介绍了C尖锐概念中的StringIsNullOrEmpty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候会发挥关键作用?我们真的需要string.IsNullOrEmpty吗?





When this will play a key role? Do we Really need string.IsNullOrEmpty ?


objClaimListApproval_SC.Reim_Token_ID =
         string.IsNullOrEmpty(txt_Token_ID.Text) ? string.Empty : txt_Token_ID.Text;

推荐答案

String.IsNullOrEmtpy 只返回true / false值取决于传入的字符串实际上是否包含任何内容。该表达式只检查字符串值的存在并返回该值。如果没有值(null)或传入的字符串与或String.Empty等效,则返回String.Empty。



您提供的代码是单行版本:

String.IsNullOrEmtpy just returns a true/false value depending on if the string passed in actually has any content. That expression just checks for the existence of a string value and returns the value. If there is no value (null) or the passed in string is equivilent to "" or String.Empty, it returns String.Empty.

The code you supplied is a single line version of:
string result;
if (string.InNullOrEmpty(txt_Token_ID.Text))
{
    result = string.Empty;
}
else
{
    result = txt_Token_ID.Text;
}





坦率地说,这段代码绝对无用,因为 TextBox.Text 永远不会返回 null 值。它总是一个0( String.Empty )或更多字符的字符串。



Frankly, this code is absolutely useless as TextBox.Text will NEVER return a null value. It's always going to be a string of 0 (String.Empty) or more characters.


它很方便。

如果你有一个接受字符串的方法:

It's handy.
If you have a method which accepts a string:
private void MyMethod(string s)
    {
    ...
    }

然后你不能直接使用字符串:

Then you can't afford to just use the string directly:

if (s.Trim() == "")
    {
    ...
    }

因为尝试在 null 值上调用Trim会导致空引用异常。

编码它为:

Because the attempt to call Trim on a null value will cause a "Null Reference" exception.
Coding it as:

if (string.IsNullOrEmpty(s))
    {
    ...
    }

避免这种情况,并进行同样的检查以确保字符串不仅仅是同时。

在.NET 4.0及更高版本中,您还可以获得:

Avoids that, and does the same check to ensure the string isn't just "" at the same time.
In .NET 4.0 and above, you also get:

if (string.IsNullOrWhitespace(s))
    {
    //...
    }

哪个更有帮助!


当然它是有用的,避免重复检查是非常有用的!

IsNullOrEmpty 是一种方便的方法,可以让你同时测试String是否为null或者它的值是空的。它等同于以下代码:
Of course it is useful, it is mostly useful to avoid the double check!
IsNullOrEmpty is a convenience method that enables you to simultaneously test whether a String is null or its value is Empty. It is equivalent to the following code:
result = s == null || s == String.Empty;

一个可能的用法是问题中的代码行,另一个可能是避免以下情况(不幸的是常见错误:

One possible usage is your line of code in the question, an other can be to avoid the following (unfortunately common) mistake:

string CheckString(string str)
{
   if (str == null) 
      return "Empty!";
   else 
      return "Not Empty";
}





干杯,

Edo



Cheers,
Edo


这篇关于C尖锐概念中的StringIsNullOrEmpty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆