c# - 没有构造函数的结构体

标签 c# struct constructor

我正在尝试使用存在以下结构的 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/

相关文章:

c# - 强制 Visual Studio 重建依赖项目

c# - 如何在 ASP.Net 中使用子控件集合创建控件

c# - 如何根据 XAML 中定义的 XMLDataProvider 数据计算平均值

c# - URL 在浏览器中有效,但无法从 Web 客户端或 Web 请求获取响应

c - C 中带有指向结构体的指针的结构体

javascript - 对象构造函数作为大对象中的函数

c# - 如何在 C# 中在运行时转换泛型值?

c# - 在 C# 中,我应该使用 struct 来包装一个对象以实现额外的接口(interface)吗?

c++ - 不确定如何在 main() 中将参数从类传递到构造函数

c++ - Dlib:如何初始化一个忽略标志设置为 1 的 mmod_rect?