关键字“ new”是什么意思在C#中执行结构? [英] What does the keyword "new" do to a struct in C#?

查看:48
本文介绍了关键字“ new”是什么意思在C#中执行结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,结构是根据值管理的,而对象是引用的。据我了解,创建类的实例时,关键字 new 使C#使用类信息来创建实例,如下所示:

In C#, Structs are managed in terms of values, and objects are in reference. From my understanding, when creating an instance of a class, the keyword new causes C# to use the class information to make the instance, as in below:

class MyClass
{
    ...
}
MyClass mc = new MyClass();

对于struct,您不是在创建对象,而只是将变量设置为值:

For struct, you're not creating an object but simply set a variable to a value:

struct MyStruct
{
    public string name;
}
MyStruct ms;
//MyStruct ms = new MyStruct();     
ms.name = "donkey";

我不明白的是,如果声明变量 MyStruct ms = new MyStruct (),这里的关键字 new 在做什么? 。如果struct不能成为对象,那么在这里实例化 new 是什么?

What I do not understand is if declare variables by MyStruct ms = new MyStruct(), what is the keyword new here is doing to the statement? . If struct cannot be an object, what is the new here instantiating?

推荐答案

struct(C#参考)


使用new运算符创建结构对象时,将创建该对象并创建适当的构造函数叫做。与类不同,可以在不使用new运算符的情况下实例化结构。如果您不使用new,则所有字段都将被初始化,否则这些字段将保持未分配状态,并且无法使用该对象。

When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

据我所知,除非使用 new ,否则您实际上将无法正确使用结构您需要确保手动初始化所​​有字段。如果使用new运算符,则正确编写的构造函数将有机会为您执行此操作。

To my understanding, you won't actually be able to use a struct properly without using new unless you make sure you initialise all the fields manually. If you use the new operator, then a properly-written constructor has the opportunity to do this for you.

希望可以将其清除。如果您需要对此进行澄清,请告诉我。

Hope that clears it up. If you need clarification on this let me know.

编辑

有相当长的评论主题,所以我想在这里再添加一些。我认为理解它的最好方法就是尝试一下。在Visual Studio中创建一个名为 StructTest的控制台项目,并将以下代码复制到其中。

There's quite a long comment thread, so I thought I'd add a bit more here. I think the best way to understand it is to give it a go. Make a console project in Visual Studio called "StructTest" and copy the following code into it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace struct_test
{
    class Program
    {
        public struct Point
        {
            public int x, y;

            public Point(int x)
            {
                this.x = x;
                this.y = 5;
            }

            public Point(int x, int y)
            {
                this.x = x;
                this.y = y;
            }

            // It will break with this constructor. If uncommenting this one
            // comment out the other one with only one integer, otherwise it
            // will fail because you are overloading with duplicate parameter
            // types, rather than what I'm trying to demonstrate.
            /*public Point(int y)
            {
                this.y = y;
            }*/
        }

        static void Main(string[] args)
        {
            // Declare an object:
            Point myPoint;
            //Point myPoint = new Point(10, 20);
            //Point myPoint = new Point(15);
            //Point myPoint = new Point();


            // Initialize:
            // Try not using any constructor but comment out one of these
            // and see what happens. (It should fail when you compile it)
            myPoint.x = 10;
            myPoint.y = 20;

            // Display results:
            Console.WriteLine("My Point:");
            Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);

            Console.ReadKey(true);
        }
    }
}

试一试。删除构造函数,看看会发生什么。尝试使用仅初始化一个变量的构造函数(我已经注释掉了一个……它将无法编译)。尝试使用和不使用 new 关键字(我已注释掉一些示例,请取消注释并尝试一下)。

Play around with it. Remove the constructors and see what happens. Try using a constructor that only initialises one variable(I've commented one out... it won't compile). Try with and without the new keyword(I've commented out some examples, uncomment them and give them a try).

这篇关于关键字“ new”是什么意思在C#中执行结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆