在C#中,我想用空字符串初始化字符串值.
我该怎么做?什么是正确的方法,为什么?
string willi = string.Empty;
Run Code Online (Sandbox Code Playgroud)
要么
string willi = String.Empty;
Run Code Online (Sandbox Code Playgroud)
要么
string willi = "";
Run Code Online (Sandbox Code Playgroud)
或者是什么?
在.NET中,String.Empty
和之间的区别是什么""
,它们是可互换的,还是存在一些基本的参考或本地化问题,这些问题String.Empty
将确保不是问题?
这是很烦人的测试我所有的字符串null
之前,我可以放心地运用类似的方法ToUpper()
,StartWith()
等...
如果默认值string
是空字符串,我就不用考了,我会觉得它是与其他价值类型,如更一致int
或double
为例子.另外Nullable<String>
有意义.
那么为什么C#的设计者选择使用null
字符串的默认值呢?
注意:这与此问题有关,但更侧重于为什么而不是如何处理它.
空字符串或空字符串 - 比表示列中没有数据的更好吗?(我特意使用MySQL,但我认为这是独立于系统的.)使用一个是否存在主要的优点/缺点,还是仅仅是程序员偏好?
对我来说,作为开发人员和用户,我发现空字符串("")无用且引起很多混乱,就像说string == char []
也许计算机需要空字符串,所以我想了解原因.
也可以看看:
这是文本文件
country1: 93#country2: 355#country3: 213#country4: 376#country5: 244#country6: 54#country7: 374#
Run Code Online (Sandbox Code Playgroud)
对于这个ASP.NET Web服务,当我声明字符串temp ouside"for"循环时,错误"使用未分配的局部变量'temp'"
[webMethod]
public string[] getContryCode ()
{
string temp;
string[] data = File.ReadAllLines(@"countryCode.txt");
string[] country = data[0].Split('#');
for (int i = 0; i < country.Length; i++ )
{
temp = country[i];
}
//const string f = "countryCode.txt";
return temp.Split(':');
}
Run Code Online (Sandbox Code Playgroud)
如果我在循环中声明字符串temp,我不能返回值"temp.Split(':')".需要找到解决它的方法
originl文件格式:#country1:code1#country2:code2#
数组列表'country':[0] country1 code1 country2 code2
- 我可以得到这个工作b split temp.split(':'):应该得到这样的东西[0]country1 [1] code1 [2] country2 [3] code2