C#中判断空字符串的几种方法

本文探讨了C#中检查字符串是否为空或空字符串的不同方法,并对比了各种方法的执行效率。通过对几种常见方式的分析,包括直接比较空字符串、使用Length属性、及调用IsNullOrEmpty方法等,帮助开发者理解其内部实现差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ContractedBlock.gifExpandedBlockStart.gifCode
 1namespace my
 2ExpandedBlockStart.gifContractedBlock.gif{
 3    class Program
 4ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 5        static void Main(string[] args)
 6ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 7            string a = string.Empty;
 8            if (a == ""//执行效率(4)
 9ExpandedSubBlockStart.gifContractedSubBlock.gif            {
10                Console.WriteLine(@"a=="" ");
11            }

12            if (a == string.Empty)//执行效率(3)
13ExpandedSubBlockStart.gifContractedSubBlock.gif            {
14                Console.WriteLine("a==string.Empty");
15            }

16            if (a.Length == 0)  //执行效率最高(1)
17ExpandedSubBlockStart.gifContractedSubBlock.gif            {
18                Console.WriteLine("a.Length == 0");
19            }

20            if (string.IsNullOrEmpty(a)) //执行效率(2) 
21ExpandedSubBlockStart.gifContractedSubBlock.gif            {
22                Console.WriteLine("a==string.Empty");
23            }

24
25           bool b =  IsNullOrEmpty(a);
26           Console.WriteLine(b);
27
28        }

29
30ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
31        /// 判断字符串是否为空
32        /// </summary>
33        /// <param name="value">String 类型的值</param>
34        /// <returns>返回值 true ,false </returns>

35        public static bool IsNullOrEmpty(string value)
36ExpandedSubBlockStart.gifContractedSubBlock.gif        {
37            if (value != null)
38ExpandedSubBlockStart.gifContractedSubBlock.gif            {
39                return (value.Length == 0);
40            }

41            return true;
42        }

43
44    }

45}

转载于:https://www.cnblogs.com/liuyong/archive/2009/05/25/1489221.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值