不同类型的琴弦 [英] Different types of Strings

查看:96
本文介绍了不同类型的琴弦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以创建和初始化字符串为

We can create and initialise strings as

String str="Hello Friends";







OR

String str=new String("Hello Friends");



我想知道,两种初始化类型之间有什么区别.



I wanna know, what is the difference between both types of initialization.

推荐答案

答案在编译器中.

使用"创建字符串时,将创建一个字符串对象.这可以通过使用String扩展名来观察.

The answer is in the compiler.

When you create a string using "" a string object is made. This can be observed by using String extensions.

public static class StringExtended
{
   public static string CustomFormat(this string s, params object[] args)
      return string.Format(intput ?? string.Empty, args);
}

...

public void DoSomething()
{
    var formatted = "Hello World{0}".CustomFormat("!");

    //Same as
    var standardFormat = string.Format("Hello World{0}", "!");
}



同样,您可以执行5.ToString()之类的操作,因为5的类型为Int32.



Similarly you can do stuff like 5.ToString() since 5 is of type Int32.


没什么.前者只是缩写形式,因为字符串很常见,因此被编译器接受.
Nothing. The former is just an abbreviated form accepted by the compiler as strings are so common.


此处第一个像变量一样使用,而另一个像使用构造函数初始化String的类一样使用.我想知道,为什么会这样呢?第一种情况是如何在后台运行的.请解释答案.
here first one is used like a variable while other like a class which is using constructor for initialising the String. I wanna know, why is it so? How the first case is working at background. please explain the answer.


这篇关于不同类型的琴弦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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