1、下面是一个结构的定义:
?
1
2
3
4
5
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
什么时候用结构:
用于小型的数据结构其中的值一般不修改2、类的定义:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Animal
{
public string Name { get; set; }
public double Weight { get; private set; }
private string _color;
public string Color
{
get { return _color; }
set { _color = value; }
}
public void MakeSound()
{
Console.WriteLine(Sound);
}
}
3、结构和类的一个区别: 现在上面两个都没有显式的构造函数,如果给它们加上显式的构造函数:
?
1
2
3
4
5
6
7
8
9
10
11
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int X, int Y)
{
this.X = X;
this.Y = Y;
}
}
如果我们进行实例化,可以发现隐式构造函数仍然可用:
?
1
2
Point p = new Point();
Point P = new Point(10, 12);
但同时我们就不能在结构中再定义一个无参数的构造函数了,