相关疑难解决方法(0)

为什么.NET String是不可变的?

众所周知,String是不可变的.String不可变的原因是什么,StringBuilder类的引入是可变的?

.net c# string immutability

182
推荐指数
8
解决办法
10万
查看次数

C#中的引用类型

考虑以下代码:

public class Program
{
    private static void Main(string[] args)
    {
        var person1 = new Person { Name = "Test" };
        Console.WriteLine(person1.Name);

        Person person2 = person1;
        person2.Name = "Shahrooz";
        Console.WriteLine(person1.Name); //Output: Shahrooz
        person2 = null;
        Console.WriteLine(person1.Name); //Output: Shahrooz
    }
}

public class Person
{
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

很显然,当分配person1person2Name物业person2发生变化,Nameperson1也将改变.person1person2有相同的参考.

为什么何时person2 = null,person1变量也不会为空?

.net c# pointers

78
推荐指数
4
解决办法
6754
查看次数

字符串对象真的是通过引用?

我正在学习(新手).NET,我有些疑惑.

从书中读到的例子我了解到String是对象,然后是Reference Type.

所以,我做了这个测试,结果与我的预期不同:

我真的很好奇,这是一个例外,因为"字符串"是特殊类型吗?

class Program
{
    static void Main(string[] args)
    {
        SByte a = 0;
        Byte b = 0;
        Int16 c = 0;
        Int32 d = 0;
        Int64 e = 0;
        string s = "";
        Exception ex = new Exception();

        object[] types = { a, b, c, d, e, s, ex };

        // C#
        foreach (object o in types)
        {
            string type;
            if (o.GetType().IsValueType)
                type = "Value type";
            else
                type = "Reference Type";
            Console.WriteLine("{0}: {1}", o.GetType(), type);
        } …
Run Code Online (Sandbox Code Playgroud)

.net c# string reference

14
推荐指数
2
解决办法
6836
查看次数

标签 统计

.net ×3

c# ×3

string ×2

immutability ×1

pointers ×1

reference ×1