V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
sophie2805
V2EX  ›  问与答

MSDN 上关于 C# struct 的一个疑惑,求解答

  •  
  •   sophie2805 · Mar 15, 2016 · 2815 views
    This topic created in 3698 days ago, the information mentioned may be changed or developed.

    https://msdn.microsoft.com/zh-cn/library/saxz13w4(v=vs.80).aspx

    新手,跟着 MSDN 上的 C#文档学习。

    关于 struct ,它写道:
    结构与类共享几乎所有相同的语法,但结构比类受到的限制更多:

    •在结构声明中,除非字段被声明为 const 或 static ,否则无法初始化。

    •结构不能声明默认构造函数(没有参数的构造函数)或析构函数。


    很是不解,这句话给我的直观感觉是: struct 的成员必须定义成 const 或者 static ,不然没办法初始化。
    但实际上 struct 的成员可以不是 const/static

    是不是我的理解有偏差。。。

    3 replies    2016-03-16 10:13:33 +08:00
    Archangel_SDY
        1
    Archangel_SDY  
       Mar 15, 2016   ❤️ 1
    是指你不能给成员字段一个初始化的值吧.
    KexyBiscuit
        2
    KexyBiscuit  
       Mar 15, 2016   ❤️ 1
    Initialize 指的是为这个 field 赋初始值, declare 是没问题的,所以 struct 的成员字段可以不是 const 或 static 。

    另外……

    请阅读 MSDN Library 的英文版并选择最新的文章版本……

    https://msdn.microsoft.com/en-us/library/saxz13w4.aspx
    wizardforcel
        3
    wizardforcel  
       Mar 16, 2016   ❤️ 1
    实例字段无法手动初始化,也不能自定义默认构造器(无参构造器)。默认构造器的行为是将所有字段赋默认值。

    c#6.0 起可以自定义默认构造器。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4275 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 54ms · UTC 09:57 · PVG 17:57 · LAX 02:57 · JFK 05:57
    ♥ Do have faith in what you're doing.