结构

 

public struct PostalAddress
{
    // Fields, properties, methods and events go here...
}

 

结构与类共享大多数相同的语法,但结构比类受到的限制更多:

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

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

·         结构在赋值时进行复制。 将结构赋值给新变量时,将复制所有数据,并且对新副本所做的任何修改不会更改原始副本的数据。 在使用值类型的集合(如 Dictionary<string, myStruct>)时,请务必记住这一点。

·         结构是值类型,而类是引用类型。

·         与类不同,结构的实例化可以不使用 new 运算符。

·         结构可以声明带参数的构造函数。

·         一个结构不能从另一个结构或类继承,而且不能作为一个类的基。 所有结构都直接继承自 System.ValueType,后者继承自 System.Object。

·         结构可以实现接口。

·         结构可用作可以为 null 的类型,因而可向其赋 null 值。

 

 1 using System;
 2  
 3 struct Point
 4 {
 5     public double x, y;
 6     public Point(int x, int y) {
 7         this.x = x;
 8         this.y = y;
 9     }
10     public double R(){
11         return Math.Sqrt(x*x+y*y);
12     }
13 }
14  
15 class Test
16 {
17     static void Main() {
18         Point[] points = new Point[100];
19         for (int i = 0; i < 100; i++)
20             points[i] = new Point(i, i*i);
21     }
22 }

 

 

来自 <http://www.icourse163.org/learn/PKU-1001663016?tid=1002052006>

 

 

 

posted @ 2018-01-20 21:50  奔跑的蒲公英  阅读(229)  评论(0编辑  收藏  举报