首页 > 解决方案 > 请帮助我使用“新”关键字

问题描述

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

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

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

标签: c#new-operator

解决方案


类和对象之间是有区别的。对象是类的实例化。

例如,如果你有一个House类,你可以有多个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.

推荐阅读