结构是一种值类型,使用struct关键字定义。

结构可以包含字段、常量、事件、属性、方法、构造函数、索引器、运算符和嵌套类型。但若结构中同时需要上述所有成员,应考虑将结构改为类。

  • 嵌套类型:在类或构造中定义的类型称为嵌套类型。

结构的构造函数中,必须对所有字段赋值,否则编译器会报错

struct Dimensions
    {
        public double length,width;
        public string testField;

        public Dimensions(double length,double width,string testField)
        {
            this.length = length;
            this.width = width;
            this.testField = testField;
        }

        public double Diagonal
        {
            get
            {
                return Math.Sqrt(length * length + width * width);
            }
        }

        public string TestProperty
        {
            get
            {
                return testField;
            }
        }
    }

可以像类一样通过new关键字对结构进行实例化。此时,若使用无参构造函数,则所有成员都分配为默认值(类也如此)。

也可以不使用new运算符。此时,结构使用前所有元素都必须进行初始化(为所有字段分别赋值),否则编译器会报错。

        static void Main(string[] args)
        {
            //通过new运算符,使用默认无参构造函数,对结构实例化
            Dimensions point = new Dimensions();
            point.length = 10;
            Console.WriteLine(point.Diagonal);
            Console.WriteLine(point.TestProperty??"显示null");

            //不使用new运算符对结构实例化
            Dimensions point2;
            point2.length = 30;
            point2.width = 10;
            point2.testField = "testField";
            Console.WriteLine(point2.Diagonal);
            Console.WriteLine(point2.TestProperty);


            TestClass test = new TestClass();
            Console.WriteLine(test.age);
            Console.WriteLine(test.Name ?? "123null");
        }

输出:

                 

注意:

  • 结构中不能初始化实例字段,静态字段可以。
  • 结构不能显示声明默认无参构造函数。
  • 结构可以实现接口。
  • 一个结构无法继承自另一个结构或类,并且不能成为类的基类。

 

参考来源:

《C#高级编程(第9版)》

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/struct

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/structs

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/using-structs

posted on 2018-02-02 10:02  雪溪  阅读(259)  评论(0编辑  收藏  举报