为什么我得到这个错误创建&返回一个新的结构体? [英] Why do I get this error creating & returning a new struct?

查看:252
本文介绍了为什么我得到这个错误创建&返回一个新的结构体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编译此代码时出现错误:

I get an error when I compile this code:

using System;

public struct Vector2
{
    public event EventHandler trigger;

    public float X;
    public float Y;

    public Vector2 func()
    {
        Vector2 vector;
        vector.X = 1;
        vector.Y = 2;
        return vector;  // error CS0165: Use of unassigned local variable 'vector'
    }
}

hi!

编译器说:使用未分配的局部变量'vector'并指向返回值。它看起来我认为Vector2成为一个引用类型(没有事件成员它正常工作)。发生了什么?

The compiler says: "Use of unassigned local variable 'vector'" and points to the return value. It looks to me that Vector2 become a reference type (without the event member it acts normally). What is happening?

推荐答案

在C#中,你还需要'new'一个结构来调用构造函数,除非你初始化全部

In C# you still need to 'new' a struct to call a constructor unless you are initializing all the fields. You left EventHandler member 'trigger' unassigned.

尝试指定为「触发」或使用:

Try either assigning to 'trigger' or using:

Vector2 vector = new Vector2()

> 在堆上分配,它仍然在函数堆栈上分配。

The new object is not allocated on the heap, it is still allocated on the functions stack.

引用 MSDN


当使用
创建一个struct对象时,new操作符将被创建,
将调用相应的构造函数。
与类不同,struct可以是
实例化而不使用新的
运算符。 如果您不使用新的,则
字段将保持未分配状态,
对象不能使用
字段已初始化。

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.

这篇关于为什么我得到这个错误创建&返回一个新的结构体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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