没有构造函数的struct

Pet*_*erJ 0 c# constructor struct

我试图使用存在以下结构的DLL:

 public struct MyStruct
 {
     public int Day;
     public int Hour;
     public int Month;
     public int MonthVal;
 }
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我试图为这些变量赋值:

MyStruct MS; OR MyStruct MS = new MyStruct(); and then do
MS.Day = 1;
MS.Hour = 12;
MS.Month = 2;
MS.MonthVal = 22;
Run Code Online (Sandbox Code Playgroud)

问题是,MS不能赋值,并且因为struct没有构造函数,我做不到

 MyStruct ms = new MyStruct(1, 12, 2, 22);
Run Code Online (Sandbox Code Playgroud)

那么,我如何获得结构中的值?

das*_*ght 5

在我的代码中,我试图为这些变量赋值

MyStruct MS = new MyStruct();
MS.Day = 1;
MS.Hour = 12;
MS.Month = 2;
MS.MonthVal = 22;
Run Code Online (Sandbox Code Playgroud)

这种方法非常有效(演示).但是,下面描述的两种方法更好:

如果您不想定义构造函数,则此语法将为您节省一些输入,并在单个初始值设定项中将相关项组合在一起:

MyStruct MS = new MyStruct {
    Day = 1,
    Hour = 12,
    Month = 2,
    MonthVal = 22
};
Run Code Online (Sandbox Code Playgroud)

如果您可以定义构造函数,请执行以下操作:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这种方法会给你一个不可变的struct(它应该是),以及一个应该被调用的构造函数:

MyStruct MS = new MyStruct(1, 12, 2, 22);
Run Code Online (Sandbox Code Playgroud)