为什么数组中的每个元素都要在c#中再次分配(Why should each element in array be allocated again in c#)

编程入门 行业动态 更新时间:2024-10-19 20:40:29
为什么数组中的每个元素都要在c#中再次分配(Why should each element in array be allocated again in c#)

以下是我写的Calc[] calculators = new Calc[10]; calculators[0].AddToSum(10); (编写相应的类和方法)。 但我得到“对象引用未设置为对象的实例”异常。然后通过一些研究我通过执行以下操作删除了异常。

for (int i = 0; i < 10; i++) { calculators[i] = new Calc(); }

有人可以解释为什么我们需要再次分配内存,这与c / c ++不同。 这就是我在c ++中的表现:

Calculator *calc=new Calculator[10]//I know I need to check for std::bad_alloc exception calculators[0].AddToSum(10); delete[] calc;

Following is the code I wrote Calc[] calculators = new Calc[10]; calculators[0].AddToSum(10); (the corresponding classes and methods are written). But I got "Object reference not set to an instance of an object" exception.Then with some research I got the exception removed by doing following.

for (int i = 0; i < 10; i++) { calculators[i] = new Calc(); }

Can somebody explain why we need to allocate memory again unlike in c/c++. This is how I did it in c++:

Calculator *calc=new Calculator[10]//I know I need to check for std::bad_alloc exception calculators[0].AddToSum(10); delete[] calc;

最满意答案

在C#中,有引用类型,并且有值类型。 类是引用类型。 创建引用类型的变量时,您将创建引用,而不是对象。 引用的默认状态为null。 如果您希望它引用一个对象,则必须使用new显式初始化它,或者从另一个初始化引用中分配if。

C ++没有这种区别。 每种类型都是值类型(尽管您也可以创建对任何类型的引用)。 创建值类型的变量时,您将创建一个对象。

In C#, there are reference types, and there are value types. Classes are reference types. When you create a variable of a reference type, you are creating a reference, not an object. The default state of a reference is null. If you want it to refer to an object, you have to explicitly initialize it with new, or assign if from another initialized reference.

C++ does not have this distinction. Every type is a value type (though you can also create references to any type). When you create a variable of a value type, you are creating an object.

更多推荐

本文发布于:2023-08-04 13:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415986.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:要在   组中   元素   分配   allocated

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!