一 结构 struct
结构常用来表示较简单的多个分量(字段)
如:
Point,Color,Size,DateTime,Int32
public struct Int32:IComparable,IFormattable,
IConvertible,ICOmparable<int>,IEquatable<int>
可以有方法、属性等其他成员。
struct Point
{
public double x,y;
public Point(int x,int y)
{
this.x=x;
this.x=y;
}
public double R()
{
return Math.Sqrt(x*x+y*y);
}
}
二 定义struct要注意
1 struct是值类型
① 结构不能包含无参数构造方法;
如 Point p;s.X=100;
② 每个字段在定义时,不能给初始值;
③ 构造方法中,必须对每个字段进行赋值;
2 struct 是sealed的,不能被继承
3 struct是值类型
① 实例化,使用new,但与引用型变量的内存不同的
Point p=new Point(100,90);
② 值类型变量在赋值时,实行的是字段的copy
Point p1,p2;
p1=p2;
三 枚举(enum)
枚举实际上是有意义的整数
如FontStyle,GraphicsUnit,KnownColor,DockStyle,DialogResult
1 定义枚举
声明自己的属性
enum myColor//(后面可以跟一个int)
{
Red,
Green=1,
Blue=2
}
2 使用枚举
赋值及比较
myColor c=myColor.Red
if(c==myColor.Red)
switch(c){
case myColor.Red:..
}
与字符串的转换
Console.WriteLine(c.ToString());
c=(myColor)Enum.Parse(typeof(myColor),"Red");
总结
结果主要用来表示多个分量;
枚举主要用来表示符合化的常量;
它们都是值类型;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 结构
{
struct Point
{
public double x, y;
public Point(int x,int y)
{
this.x = x;
this.y = y;
}
public double R()
{
return Math.Sqrt(x * x + y * y);
}
}
class Test
{
static void Main()
{
Point[] points = new Point[100];
for (int i = 0; i < 100; i++)
points[i] = new Point(i, i * i);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 枚举
{
enum LightColor
{
Red,
Yellow,
Green
}
class TrafficLight
{
public static void WhatInfo(LightColor color)
{
switch(color)
{
case LightColor.Red:
Console.WriteLine("Stop!");
break;
case LightColor.Yellow:
Console.WriteLine("Warning!");
break;
case LightColor.Green:
Console.WriteLine("Go!");
break;
}
}
}
class Test
{
static void Main()
{
LightColor c = LightColor.Red;
Console.WriteLine(c.ToString());
TrafficLight.WhatInfo(c);
Console.ReadKey();
}
}
}