我在编译期间遇到struct问题。我在c#中编程并使用Visual Studio 2003. From MSDN:
使用new运算符创建struct对象时,会创建它并调用相应的构造函数。与类不同,可以在不使用new运算符的情况下实例化结构。如果不使用new,则字段将保持未分配状态,并且在初始化所有字段之前无法使用该对象。
您可以在没有new()语句的情况下实例化一个struct;在我的电脑上它完美的工作,而在另一台电脑上我看到编译错误(需要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的一些环境变量中。
答案 0 :(得分: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是字段,而不是属性。您必须在使用结构之前分配所有字段。如果您要包含自动属性,例如,您无权访问基础字段,那么就不可能。