字符串VS类时都是引用类型都是、字符串、类型、VS

由网友(余孽)分享简介:这是我最后一次采访了如何去:Here is how my last interview went:问:在哪里字符串存储在哪里? Question: Where are strings stored? 答:堆,因为它是引用类型Answer: Heap since it is a reference type问:解释...

这是我最后一次采访了如何去:

Here is how my last interview went:

问:在哪里字符串存储在哪里?

Question: Where are strings stored?

答:堆,因为它是引用类型

Answer: Heap since it is a reference type

问:解释我这下code:

Question: Explain me this following code:

static void Main(string[] args)
{
     string one = "test";
     string two = one;
     one = one + " string";

     Console.WriteLine("One is {0}" , one);
     Console.WriteLine("Two is {0}", two);
}

答:德鲁两个图如下图所示:

Answer: Drew two diagrams like below:

(重presents的声明,线二=之一;

(represents the statement, string two = one;

(重presents的声明,一等于一+字符串。新字符串堆创建和分配)

(represents the statement, one = one + " string";. A new string is created on heap and assigned)

问:正确的。绘制相似低于code片断:

Question: Correct. Draw similar for the code snippet below:

class Program
{
    static void Main(string[] args)
    {
        Test one = new Test { someString = "test" };
        Test two = one;
        one.someString = "test String";

        Console.WriteLine("One is {0}", one.someString);
        Console.WriteLine("Two is {0}", two.someString);
    }
}

class Test
{
    public string someString { get; set; }
}

答:

[测试二=一个]

[Test two = one]

one.someString = "test String";

问:确定。你说这两个字符串是引用类型。那么,为什么对字符串的新对象被创建并分配而对于类的价值,现有的字符串属性本身被修改?

Question: Ok. You said both strings and classes are reference types. Then why did a new object for string is created and assigned the value whereas for class, the existing string property itself gets modified ?

答:因为字符串是不可变的,而类是可变的。

Answer: Because strings are immutable whereas classes are mutable.

(虽然我清除了采访,我还是不明白这种行为。为什么类的设计使其可变,同时保持弦不变?有很多therotical答案随处可见,但可以任何一个使简单通过解释上述code)这个特殊的行为吗?

(Though I cleared the interview, I still did not understand this behaviour. Why did the designers of class make it mutable while keeping strings immutable ? There are a lot of therotical answers everywhere, but could any one make it simple by explaining this particular behaviour with the above code ?)

推荐答案

一个原因琴弦作了不变的,即使他们是引用类型,是使它们的外观和行为像基本类型(例如,INT,双,浮法)。

One of reasons strings were made immutable, even though they are reference types, was to make them look and behave like primitive types (e.g., int, double, float).

这也是为什么字符串是可以重新psented作为文字$ P $的唯一引用类型的原因(例如,一些字符串)。很多其他语言的采取同样的方法,像Java为例。

That's also the reason why strings are the only reference type that can be represented as a literal (e.g., "some string"). Lots of other languages take the same approach, like Java for example.

阅读全文

相关推荐

最新文章