来源:http://mcdelfino.blog.51cto.com/2058744/661072
不能为结构声明默认构造函数(一个无参数的构造函数).因为编译器始终会帮我们生成一个.在类中只有在没有自己写一个构造函数的前提下,编译器才 会帮我们生成一个默认构造函数.在编译器为结构生成的默认构造函数中,总是将字段设为0,false或者null,这和类是一样的.然而,在自己写的一个 构造函数中(再次提醒,这必须是一个非默认的构造函数),必须自己负责初始化所有字段,编译器不会再帮我们初始化它.这意味着必须在结构的所有非默认构造 函数中显式地初始化所有字段,否则会造成编译时错误.例如,假定把Time换成一个类,那么下面的例子是能通过编译的,而且seconds会被悄悄地初始 化为0.但是,由于Time是一个结构,所以它无法通过编译:
- struct Time
- {
- public Time(int hh, int mm)
- {
- hours = hh;
- minutes = mm;
- //seconds = 0;
- }
- public int hours, minutes, seconds;
- }
修改:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- Time time0 = new Time();
- Console.WriteLine("{0}:{1}:{2}", time0.hours, time0.minutes, time0.seconds);
- Time time1 = new Time(6, 25);
- Console.WriteLine("{0}:{1}:{2}", time1.hours, time1.minutes, time1.seconds);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- struct Time
- {
- public Time(int hh, int mm)
- {
- hours = hh;
- minutes = mm;
- seconds = 0;
- }
- public int hours, minutes, seconds;
- }
- }
- }
若是将Time声明为一个类,则可以不用将全部字段初始化,但是不会默认有无参数的构造函数,因此要自己写一个无参数的构造函数.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- Time time0 = new Time();
- Console.WriteLine("{0}:{1}:{2}", time0.hours, time0.minutes, time0.seconds);
- Time time1 = new Time(6, 25);
- Console.WriteLine("{0}:{1}:{2}", time1.hours, time1.minutes, time1.seconds);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- }
- class Time
- {
- public Time()
- {
- } //要定义无参数的构造函数,不会默认生成
- public Time(int hh, int mm)
- {
- hours = hh;
- minutes = mm;
- } //可以不必将所有字段都初始化,会默认初始化为0
- public int hours, minutes, seconds;
- }
- }