Visual Studio 2003 C#, struct compiling erro

本文关键字:struct compiling erro Studio 2003 Visual | 更新日期: 2023-09-27 18:32:43

我在编译过程中遇到了结构问题。我用c#编程并使用Visual Studio 2003。 从 MSDN:

使用 new 运算符创建结构对象时,将创建该对象并调用相应的构造函数。与类不同,可以在不使用 new 运算符的情况下实例化结构。如果不使用 new,则字段将保持未分配状态,并且在初始化所有字段之前无法使用对象。

您可以在没有 new() 语句的情况下实例化结构;在我的 PC 上它运行良好,而在另一台 PC 上,我看到编译错误(需要 new())。Visual Studio 的環境中是否有一些筛选器或標誌(如 TreatWarningsAsErrors)可以生成此行為?

举个例子:

using System;
using System.Collections;
namespace myApp.Utils
{
    ....
    public struct StructParam
    {
        public int iIndex;
        public int[] iStartNoteArray;
        public int[] iFinalNoteArray;
        public int[] iDimension;
        public int[] iStartSequence;
        public ArrayList m_iRowIncValueArray;   
    };
    ....
}
--------------------------------------------------------------
--------------------------------------------------------------
using System;
using System.Collections;
using myApp.Utils;
namespace myApp.Main
{
    ....
    public class frmMain : System.Windows.Forms.Form
    {
        ....
        static void Main() 
        {
            ....
            StructParam oStructParam;
            oStructParam.iIndex = 0;
            oStructParam.iStartNoteArray = new int[]{0, 0};
            oStructParam.iFinalNoteArray = new int[]{0, 0};
            oStructParam.iDimension = new int[]{0, 0};
            oStructParam.iStartSequence = new int[]{0, 0};
            oStructParam.m_iRowIncValueArray = new ArrayList();
            ArrayList myArray = new ArrayList();
            myArray.Add(oStructParam);
            ....
        }
        .....
    }
    ....
}

我不认为问题出在代码上,而在于某些Visual Studio的环境变量。

Visual Studio 2003 C#, struct compiling erro

若要在不调用 new 的情况下使用结构,必须先分配其所有成员。

例如

struct Point
{
    public int x;
    public int y;
    public int DoSomething() { return x * y; }
}
Point p;
p.x = 1;
p.y = 2;
p.DoSomething();

请注意,这里的 x 和 y 是字段,而不是属性。在使用结构之前,必须分配所有字段。如果要包含自动属性,例如,您无权访问基础字段,则不可能。