String.Empty和“"”之间的区别 [英] Difference between String.Empty and ""?

查看:122
本文介绍了String.Empty和“"”之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!String.Empty和之间有什么区别?

例如,



 string s1 = String.Empty; 
string s2 =;

解决方案

出于各种原因,通常不赞成在代码中放置魔术值(其中一些已经解释过了)。虽然string.Empty看起来像一个稍微不同的野兽(例如,因为你实际上没有能力修改常量,这是使用常量的原因之一)。



这是一个实际的区别:您可以右键单击string.Empty并执行查找所有引用以查找代码中使用空字符串的位置。使用双引号分配的空字符串不能这样做。



另外,如果你试图从你的代码中删除魔术值,你也可以使用这个现有的常量,以便空字符串不会在您的代码中搜索不应该存在的引号时绊倒您(例如,如果您有一个包含所有字符串的类,例如资源文件被转换为class,你可以搜索所有其他文件,以确保它们不包含引号。)


添加到 ashokbusybee corectly说,有些情况你必须使用,例如:

 [DefaultValue( )] 
public string MyStringProperty
{
// 访问者
}



T.要把 string.Empty 放在那里!


string.empty处理内存的效率比字符串x =;

实际上创建了一个对象,但string.empty没有。



此外,避免像这样的硬编码是最佳做法;

Hi everyone!What is the difference between String.Empty and ""?
for example ,

string s1=String.Empty;
string s2="";

解决方案

Placing magic values in code is typically frowned upon, for a variety of reasons (some of which have already been explained). Though string.Empty seems like a slightly different beast (e.g., because you do not actually have the ability to modify the constant, which is one of the reasons for using constants).

Here is one practical difference: you can right click on "string.Empty" and do a "find all references" to find where empty strings are used in your code. You cannot do that with an empty string assigned using double quotes.

Also, if you are trying to remove magic values from your code, you might as well make use of this existing constant so that empty strings don't trip you up when searching through your code for quotes that should not be there (e.g., if you have a single class that holds all your strings, such as a resource file that gets translated into a class, you could search all other files to ensure they don't contain quotes).


Adding to what ashokbusybee corectly said, there are instances when you must use "", for example:

[DefaultValue("")]
public string MyStringProperty
{
    // Accessors
}


Try to put string.Empty there!


string.empty handles memory efficently than string x="";
"" actually creates an object but string.empty does not.

Also, it is a best practise to avoid hardcoding like "";


这篇关于String.Empty和“"”之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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