【求解惑】两个null数据相加的结果的疑问:
代码如下:
- C# code
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Null值相加{ class Program { static void Main(string[] args) { string str1 = null; string str2 = null; string str3 = str1 + str2; Console.WriteLine("==>两个为null的字符串相加的结果:\n==>" + (str3 == null ? "null" : (str3.ToString() == string.Empty ? "string.Empty --> 居然为长度为0的字符串。" : str3.ToString())) + System.Environment.NewLine); Console.WriteLine("==>相加后字符串[str3]的长度为:" + str3.Length + System.Environment.NewLine); Console.WriteLine("==>我操,这是什么原因??????\n\n==>按任意键继续......\n\n=====================\n"); int? a = null; int? b = null; int? c = a + b; Console.WriteLine("==>两个可空的[int]类型相加的结果:\n" + (c == null ? "==>两个可空的[int]相加结果为null" : "没猜出来是什么结果") + System.Environment.NewLine); Console.WriteLine("==>我操,这又是什么原因??????\n\n==>按任意键退出......\n\n"); Console.ReadKey(); } }}
输出结果未下:
[解决办法]
你以为加号都是一个含义啊,操作数不同,加号重载的方法就不一样,当加号的左边或右边含有字符串的时候,总是返回一个不为空的字符串。当加号左右两边都是数值的时候,就会对其进行数学运算,null+任何数都为null。
[解决办法]
- C# code
int? a = null; int? b = null; int? c = a + b;