如何在 C# 中为结构设置默认值? [英] How to make a default value for the struct in C#?
问题描述
我正在尝试为我的结构设置默认值.例如 Int 的默认值 - 0,DateTime 的默认值 - 1/1/0001 12:00:00 AM.众所周知,我们不能在结构中定义无参数构造函数.
I'm trying to make default value for my struct. For example default value for Int - 0, for DateTime - 1/1/0001 12:00:00 AM. As known we can't define parameterless constructor in structure.
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);
}
}
如何为 struct 设置默认值?
How can I make a default value for struct?
推荐答案
你不能.结构总是预先归零,并且不能保证构造函数会被调用(例如 new MyStruct[10]
).如果您需要零以外的默认值,则需要使用类.这就是为什么您不能首先更改默认构造函数的原因(直到 C# 6) - 它永远不会执行.
You can't. Structures are always pre-zeroed, and there is no guarantee the constructor is ever called (e.g. new MyStruct[10]
). If you need default values other than zero, you need to use a class. That's why you can't change the default constructor in the first place (until C# 6) - it never executes.
最接近的是使用 Nullable
字段,并通过属性将它们解释为具有一些默认值:
The closest you can get is by using Nullable
fields, and interpreting them to have some default value if they are null through a property:
public struct MyStruct
{
int? myInt;
public int MyInt { get { return myInt ?? 42; } set { myInt = value; } }
}
myInt
仍然预先归零,但您将零"解释为您自己的默认值(在本例中为 42).当然,这可能完全是不必要的开销:)
myInt
is still pre-zeroed, but you interpret the "zero" as your own default value (in this case, 42). Of course, this may be entirely unnecessary overhead :)
对于Console.WriteLine
,它只是调用虚拟的ToString
.您可以更改它以返回任何您想要的东西.
As for the Console.WriteLine
, it simply calls the virtual ToString
. You can change it to return it whatever you want.
这篇关于如何在 C# 中为结构设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!