如何在.NET中制造一个空字符串? [英] How to manufacture an empty string in .NET?

查看:35
本文介绍了如何在.NET中制造一个空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一段优化的代码,其中包含 null 和空字符串的特殊情况.我现在正在尝试为此代码编写单元测试.为此,我需要两个空的(零长度)字符串对象,它们是不同的对象.像这样:

I have written a piece of optimized code that contains special cases for null and empty strings. I am now trying to write a unit test for this code. In order to do that, I need two empty (zero-length) string objects that are different objects. Like this:

string s1, s2;
Assert.IsTrue(s1.Length == 0 && s2.Length == 0);
Assert.IsTrue(!ReferenceEquals(s1, s2));

事实证明,大多数.NET Framework API字符串都在检查空结果.在所有这些情况下,它们都返回 string.Empty .例如,"x" .Remove(0,1)返回 string.Empty .

It turns out that most .NET Framework APIs string are checking for an empty result. They are returning string.Empty in all those cases. For example, "x".Remove(0, 1) returns string.Empty.

如何创建新的零长度字符串对象?

How can I create fresh zero-length string objects?

推荐答案

您可以使用过时的方法字符串.复制

You can use the Obsolete method String.Copy

string s1 = "";
string s2 = String.Copy("");
Assert.IsTrue(s1.Length == 0 && s2.Length == 0);
Assert.IsTrue(!ReferenceEquals(s1, s2));

这篇关于如何在.NET中制造一个空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆