为什么String类没有无参数的构造函数? [英] Why does the String class not have a parameterless constructor?

查看:492
本文介绍了为什么String类没有无参数的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int object 具有无参数构造函数。为什么不使用 string

int and object have a parameterless constructor. Why not string?

推荐答案

更新:

为您提供更多信息。

您没有带 string 的空构造函数,但是您确实有 String.Empty 。原因是因为 string 是您修改的 string 的每个实例的不可变对象实际上是在内存中创建一个新的 string

You don't have an empty Constructor with a string, however you do have String.Empty. The reason is because a string is an immutable object every instance of a string you modify is actually creating a new string in memory.

例如: string name = ; ,尽管它是一个空的字符串,但仍会保留 20个字节。其中 string.Empty 只能容纳 4 8个字节。因此,尽管它们含义相同,但一个效率却更高。

For instance: string name = ""; though it is an empty string it will still hold around twenty bytes. Where the string.Empty will only hold around four or eight bytes. So though they mean the same thing, one is more efficient than the other.

但是,我相信您希望一个空的构造函数执行可能更常见的操作 StringBuilder 。可以在两者之间找到一些非常好的用法此处(确定性能命中率/使用率)。

However I believe you want an empty Constructor to do manipulation that may be more commonly handled by the StringBuilder. Some really nice usage between the two can be found here (Determine performance hit / usage).

字符串上的一些其他信息此处找到code>。它们是不可变的,因此以后不能更改内容

示例:

string first = "Greg "; // Creates string "first" in memory.
string last = "Arrigotti "; // Creates string "last" in memory.
string name = first + last; // Creates string "name" in memory.

在编辑其中之一时,它只是在创建一个全新的字符串在内存中。例如,如果您正在寻找一种可能在不存在中间名的字段中处理用户数据的方法,则空字符串可能包含有效用法。

As you edit one of these, it is simply creating a whole new string in memory. If you are looking at a way to potentially handler user data in a field where no middle name exist for instance, the empty string may contain valid usage.

希望这些指出您朝着正确的方向。

Hopefully these point you in the proper direction.

这篇关于为什么String类没有无参数的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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