gpt4 book ai didi

c# - 检查字符串是否为空的最佳方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 18:16:31 24 4
gpt4 key购买 nike

检查字符串是否为空

var test = string.Empty; 
if (test.Length == 0) Console.WriteLine("String is empty!");
if (!(test.Any())) Console.WriteLine("String is empty!");
if (test.Count() == 0) Console.WriteLine("String is empty!");
if (String.IsNullOrWhiteSpace(test)) Console.WriteLine("String is empty!");
  1. 以上所有语句产生相同的输出。我应该使用什么最佳方法?

    var s = Convert.ToString(test);    
    s = test.ToString(CultureInfo.InvariantCulture);
  2. 同样,这两个语句做同样的事情。什么是最好的使用方法?

我试过调试以及如何对 C# 语句的性能进行基准测试?

最佳答案

首先,这 4 位州长并没有在所有输入上给出相同的输出。尝试 null,前 3 个将抛出异常。并尝试 whithspaces 最后一个会给你一个失败的结果。所以你真的必须考虑你想要什么。最好的方法通常是:

string.IsNullOrEmpty
string.IsNullOrWhiteSpace

只有当您执行此操作数百万次时,您才应该了解如何进一步优化您的代码。

这里是一些测试结果,但这在任何 .net 版本上都可能不同:

1亿次迭代的测试结果:

Equality operator ==:   796 ms 
string.Equals: 811 ms
string.IsNullOrEmpty: 312 ms
Length: 140 ms [fastest]
Instance Equals: 1077 ms

source

关于c# - 检查字符串是否为空的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13266397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com