如何在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
字段,并通过属性将它们解释为具有某些默认值(如果它们为null):
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.