在C#中检查空字符串的最佳方法 [英] Most advisable way of checking empty strings in C#

查看:77
本文介绍了在C#中检查空字符串的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查空字符串的最佳方法是什么(我不是考虑在C#中初始化!),考虑代码性能?(请参见下面的代码)

What is the best way for checking empty strings (I'm not asking about initializing!) in C# when considering code performance?(see code below)

string a;

// some code here.......


if(a == string.Empty)

if(string.IsNullOrEmpty(a))

if(a == "")

任何帮助将不胜感激。 :)

any help would be appreciated. :)

推荐答案

请勿将字符串与 String.Empty 检查空字符串。

Do not compare strings to String.Empty or "" to check for empty strings.

相反,使用 String.Length == 0

Instead, compare by using String.Length == 0

string.Empty 之间的差异很小。 String.Empty 不会创建任何对象,而 会在内存中创建一个用于检查的新对象。因此string.empty在内存管理中更好。
但是与 string.Length == 0 的比较将更快,并且是检查空字符串的更好方法。

The difference between string.Empty and "" is very small. String.Empty will not create any object while "" will create a new object in the memory for the checking. Hence string.empty is better in memory management. But the comparison with string.Length == 0 will be even faster and the better way to check for the empty string.

这篇关于在C#中检查空字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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