相反,null 字符串并不引用 System.String 对象的实例,任何对 null 字符串调用方法的尝试都会生成 NullReferenceException。 但是,可以在串联和比较操作中将 null 字符串与其他字符串一起使用。
private static void Main(string[] args)
{
const string s1 = "Hi, Fanguzai!";
string s2 = null;
var s3 = string.Empty;
var s4 = s1 + s2; //有值的字符串与 null 拼接
Console.WriteLine("s4: {0}", s4);
Console.WriteLine("");
var isTrue = (s2 == s3);
Console.WriteLine("isTrue: {0}", isTrue);
Console.WriteLine();
var s5 = s3 + s2;
Console.WriteLine("s5: {0}", s5);
Console.WriteLine();
Console.Read();
}

可提高性能的 StringBuilder
.NET 中的字符串操作已高度优化,大多数情况下不会显著影响性能。但在某些应用场景中,例如在执行数百甚至好几亿次的循环中,字符串操作很可能会影响性能。 StringBuilder 类创建了一个字符串缓冲区,用于在程序执行大量字符串操作时提供更好的性能。 StringBuilder 字符串可以重新分配个别字符(内置字符串数据类型所不支持的字符)。例如,此代码在不创建新字符串的情况下更改了一个字符串的内容:
static void Main(string[] args)
{
var sb = new StringBuilder("~ Hi! Fanguzai!");
sb[0] = '^';
Console.WriteLine(sb);
Console.Read();
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持ASPKU!
注:相关教程知识阅读请移步到c#教程频道。










