c# - 如何在 C# 中为结构设置默认值?

标签 c# struct

我正在尝试为我的结构设置默认值。 例如,Int 的默认值 - 0,DateTime 的默认值 - 1/1/0001 12:00:00 AM。 众所周知,我们不能在结构中定义无参数构造函数。

struct Test
{
    int num;
    string str;
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(default(Test)); // shows namespace and name of struct test.Test
        Console.WriteLine(new Test()); // same

        Console.ReadKey(true);
    }
}

如何为结构设置默认值?

最佳答案

你不能。结构总是预先置零,并且不能保证构造函数会被调用(例如 new MyStruct[10])。如果您需要零以外的默认值,则需要使用一个类。这就是为什么您不能首先更改默认构造函数(直到 C# 6)——它永远不会执行。

最接近的方法是使用 Nullable 字段,如果它们通过属性为 null,则将它们解释为具有一些默认值:

public struct MyStruct
{
  int? myInt;

  public int MyInt { get { return myInt ?? 42; } set { myInt = value; } }
}

myInt 仍然预置零,但您将“零”解释为您自己的默认值(在本例中为 42)。当然,这可能是完全不必要的开销:)

至于Console.WriteLine,它只是调用虚拟的ToString。您可以更改它以根据需要返回它。

关于c# - 如何在 C# 中为结构设置默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39846708/

相关文章:

c# - 返回带有列表对象的列表对象

c - 使结构在库和应用程序中都可见 - C

c++ - 使用模板结构作为命名空间

c# - 可变结构与类?

C:包含动态分配成员的结构的范围?

c# - 获取对数组内部结构的引用

c# - 用不同的方法访问一个对象的好方法是什么

c# - ConcurrentBag<T> 实现中是否存在内存泄漏?

c# - ComboBox DataBinding 导致 ArgumentException

c# - 无法验证 Windows Live 帐户 Windows Azure AD