请帮我输入 "new" 关键字

Please help me with the "new" keyword

我是 c# 的新手,但我真的很想了解 c# 中的“new”关键字以了解将来如何使用它,我看过很多关于 c# 使用 new 关键字的基本视频,但我只是在没有任何知识的情况下复制它们,这让我很不舒服,我在 google 上搜索了很多但只理解了一些东西,对我来说最难理解的是“它创建了一个新的空对象”,可以有人帮我解释一下吗?

如果我没有任何构造函数,为什么我不能像这样创建一个对象

Class1 student = Class1(); //i got an error with this but it's still not help me understand the new keyword

我什么时候需要创建这样的数组

string[] myArr = new string[0];

不是这样的

string[] myArr = {};

如果有人能给我一些简单易懂的例子就好了:P 每次我搜索新关键字时,我的大脑都会想太多 :'D

Classes 和 Objects 是有区别的。 对象是 Class.

的实例化

例如,如果您有一个 House class,您可以有多个基于它的 House-对象。 每次你想创建(打个比方:建造)一座新房子,你都必须使用 new 关键字。

例如:

House myHouse = new House();
myHouse.openDoor(); //Opens the door of house 1

House neighboursHouse = new House(); //My neighbour likes to live in a house too, but I dont want him in my house. I create a new House.
neighboursHouse.ringDoorbell() // I don't have a key to my neighbours house.

new 对于初学者来说很难理解。我已经学习 C++ 和 C# 3 年了,但我仍然不确定。但是根据我的理解,使用int array[5];int[] array = new int[5];的主要区别是前者是栈分配的内存,后者是堆分配的内存。堆栈内存在编译期间分配,堆分配在程序 运行 时完成。我第一次了解到这种差异是在我发现您可以这样做时:

int x = 5;
int[] array = new int[x]

当您使用 new 关键字创建数组时,数组的长度不需要是编译时常量。 new关键字用于实例化一个class的对象,但是ClassName newObject;ClassName newObject = new ClassName;的主要区别是前者是栈分配,后者是堆分配。你可以在 C++ 中使用,但我相信你只能在 C# 中使用堆分配。

如有错误,欢迎大家在评论中指正。我不是专家,我的理解也可能有缺陷:)

new语句用于创建对象或调用之前创建的对象。 例如:

 class Program
{
    static void Main(string[] args)
    {
        Class1 class1 = new Class1();
        class1.writesomething();

        string[] myArr = new string[2];
        myArr[0] = "string text";
        myArr[1] = "other string text";
        string[] newArr = myArr;
        Console.WriteLine(newArr[0]);
        Console.WriteLine(newArr[1]);
        Console.ReadLine();
    }
}

public class Class1
{
  public void writesomething(string text = "cool text")
    {
        Console.WriteLine(text);
    }
}

如果你放置断点,你会看到 newarr 得到值 myarr