我正在尝试使用存在以下结构的 dll:
public struct MyStruct
{
public int Day;
public int Hour;
public int Month;
public int MonthVal;
}
在我的代码中,我试图为这些变量赋值:
MyStruct MS; OR MyStruct MS = new MyStruct(); and then do
MS.Day = 1;
MS.Hour = 12;
MS.Month = 2;
MS.MonthVal = 22;
问题是,MS不能被赋值,而且由于结构没有构造函数,我不能这样做
MyStruct ms = new MyStruct(1, 12, 2, 22);
那么,如何将值放入结构中?
最佳答案
In my code I am trying to assign values to these variables
MyStruct MS = new MyStruct(); MS.Day = 1; MS.Hour = 12; MS.Month = 2; MS.MonthVal = 22;
这种方法非常有效 (demo)。但是,下面描述的两种方法更好:
如果您不想定义构造函数,此语法将为您节省一些输入,并将相关项组合在一个初始值设定项中:
MyStruct MS = new MyStruct {
Day = 1,
Hour = 12,
Month = 2,
MonthVal = 22
};
如果您可以定义构造函数,请改为:
public struct MyStruct {
public int Day {get;}
public int Hour {get;}
public int Month {get;}
public int MonthVal {get;}
public MyStruct(int d, int h, int m, int mv) {
Day = d;
Hour = h;
Month = m;
MonthVal = mv;
}
}
这种方法会给你一个不可变的 struct
( which it should be ),以及一个应该像这样调用的构造函数:
MyStruct MS = new MyStruct(1, 12, 2, 22);
关于c# - 没有构造函数的结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35299796/