如何检查字符串是否为空

2

本文介绍了如何检查字符串是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想知道是否有特殊的方法/技巧来检查 String 对象是否为空.我知道 String.IsNullOrEmpty 方法,但我想将 null 字符串与空字符串 (="") 区分开来.

I am wondering if there is a special method/trick to check if a String object is null. I know about the String.IsNullOrEmpty method but I want to differentiate a null String from an empty String (="").

我是否应该简单地使用:

Should I simply use:

if (s == null) {
    // blah blah...
}

...或者有其他方法吗?

...or is there another way?

推荐答案

object 不能为 null - 表达式 的值可以为 null.值得在您的脑海中清楚地说明差异.s 的值不是一个对象 - 它是一个 reference,它要么是 null,要么指向一个对象.

An object can't be null - the value of an expression can be null. It's worth making the difference clear in your mind. The value of s isn't an object - it's a reference, which is either null or refers to an object.

是的,你应该使用

if (s == null)

请注意,这仍将使用字符串中定义的重载 == 运算符,但这样做是正确的.

Note that this will still use the overloaded == operator defined in string, but that will do the right thing.

这篇关于如何检查字符串是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14