0

我在编译期间遇到结构问题。我用 c# 编程并使用 Visual Studio 2003。 来自 MSDN

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

您可以在没有 new() 语句的情况下实例化结构;在我的电脑上它可以完美运行,而在另一台电脑上我看到编译错误(需要 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 的环境变量。

4

1 回答 1

3

要在不调用 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 是字段,而不是属性。在使用该结构之前,您必须分配所有字段。如果您要包含一个自动属性,例如,您无权访问基础字段,那么这是不可能的。

于 2013-09-25T15:22:27.273 回答