[英]What does the new operator mean in this code
I'm newbe C# student, when I studied code-reading I have a problem this code我是新手 C# 学生,当我学习代码阅读时,我对这段代码有疑问
public class Solution {
public int solution(int[] priorities, int location)
{
int answer = 0;
Queue<KeyValuePair<int, int>> que = new Queue<KeyValuePair<int, int>>();
for(int i = 0; i < priorities.Length; i++)
{
que.Enqueue(new KeyValuePair<int, int>(i, priorities[i]));
}
}
As I know the new
operator operates to create instance in reference type object like this code:据我所知, new
操作员操作以创建引用类型 object 的实例,如下代码:
Queue<KeyValuePair<int, int>> que = new Queue<KeyValuePair<int, int>>();
(so que
is made in stack and new
allocates memory in heap <-- I've learnt like this) (所以que
是在堆栈中创建的,并且new
在堆中分配 memory <--我已经学会了这样)
but:但:
que.Enqueue(new KeyValuePair<int, int>(i, priorities[i]))
In this code new
acts without variables.在这段代码中, new
行为没有变量。
(Ps. I found the KeyValuePair<> is struct type I wonder why value type use "new"... we don't use "new" in value type like int a= new 3
) (Ps。我发现 KeyValuePair<> 是结构类型我想知道为什么值类型使用“new”......我们不在像int a= new 3
这样的值类型中使用“new”)
I want know what happens我想知道会发生什么
plz teach me请教我
thank you谢谢你
The expression new MyType()
creates an instance of MyType
- that is where memory is allocated.表达式new MyType()
创建了MyType
的一个实例——这是 memory 被分配的地方。
When you write MyType m =...
you just assign something to a variable.当您编写MyType m =...
时,您只需将某些内容分配给变量。 This does not allocate anything.这不会分配任何东西。
So those two expressions are completely independent.所以这两个表达式是完全独立的。 You can assign something you didn´t create (directly) before:您可以分配以前没有(直接)创建的东西:
MyType m = new MyType();
MyType m2 = m; // just re-reference the instance created above, no memory allocation here
and you can also create an object and don´t do anything with it (although this is usually a bad idea):你也可以创建一个 object 并且不要对它做任何事情(尽管这通常是一个坏主意):
new MyType();
In the case of que.Enqueue(new KeyValuePair<int, int>(i, priorities[i]))
you create a KeyValuePair
, but assign it to the methods item
-parameter.在que.Enqueue(new KeyValuePair<int, int>(i, priorities[i]))
的情况下,您创建一个KeyValuePair
,但将其分配给方法item
-参数。
You could also store that object into a new variable and pass that to the method:您还可以将该 object 存储到一个新变量中并将其传递给该方法:
var kv = new KeyValuePair<int, int>(i, priorities[i]);
que.Enque(kv);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.