C# struct结构类型

struct(结构)类型,是一种复杂的数据类型。它可以包含简单数据类型,也可以包含其他结构类型,以及方法、属性、索引器等。

1、struct结构类型是值类型,这也是与类最重要的区别。

2、结构类型可以实现接口,却无法继承另外一个结构。

3、结构类型成员,不能被声明为protected。

4、结构类型中,不能包含其自身。

结构类型定义简单的例子如下:

public struct point
        {
            public int x;
            public int y;
        }

point p;  //声明了一个point类型的结构变量p,可以通过p.x 和 p.y 访问。

//包含point类型结构
        public struct Rectangle
        {
            public point topLeft; 
            public point topRight;
            public bool boRec;
        }

Rectangle rec; //声明了一个Rectangle 类型的结构变量rec, 可以通过rec.topLeft.x 和 rec.topLeft.y 访问所包含结构中的变量。

下面是定义结构的构造函数:

 public struct point
        {
            public int x;
            public int y;
            public point(int x,int y) //定义构造函数
            {
                this.x = x; //对成员赋值
                this.y = y;
            }
        }
point p = new point(3, 5); //使用自定义构造函数初始化      


 

原文地址:https://www.cnblogs.com/han1982/p/2697619.html