如何在C#中为结构体设置默认值? [英] How to make a default value for the struct in C#?

查看:1202
本文介绍了如何在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.

这篇关于如何在C#中为结构体设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆