关键字“new"是什么意思?对 C# 中的结构做些什么? [英] What does the keyword "new" do to a struct in C#?

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

问题描述

在C#中,Structs是按值管理的,而对象是按引用的.根据我的理解,在创建类的实例时,关键字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();

对于结构体,您不是在创建对象,而只是将变量设置为一个值:

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?

推荐答案

来自 结构(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天全站免登陆