c# - 请帮助我使用“新”关键字
问题描述
我是 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
解决方案
类和对象之间是有区别的。对象是类的实例化。
例如,如果你有一个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.
推荐阅读
- python-3.x - 计算来自不同数据帧的单元格的平均值
- c# - Asp.net 核心中是否有像 Laravel 这样的队列和作业?
- c - Iterator for red-black binary search tree in C
- node.js - VS Code Node.js debugger immediately exits if nothing anywhere in the code "forces" the main event loop to be active
- highcharts - How we design 3d column chart in highcharts like in pic?
- html - 如何删除最后一行块的边距底部?
- python - Seaborn's heatmap when annot=True displays 0, instead of 0.0. How do I change this?
- c++ - Passing a 2D array to a function / constructor
- go - Check validity of SSL self-signed certificate
- asp.net-core - Register Service in ASP.NET Core as part of a middleware registration