C# 結構struct總結
1.結構是值類型,而且是密封的,不能繼承和派生。
2.結構申明:
struct StructName
{
MemberDeclaration
}
struct Point
{
public int x ; //結構中字段初始化是不允許的
pub int y ;
}
3.結構具有以下特點
(1)結構與類非常類似,但是結構是值類型,類是引用類型。
(2)結構實例化可以不適用new運算符。但是在顯示設置數據成員之后,才能調用他們的值。
(3)系統已經為結構提供一個隱式構造函數(無參數),所以結構申明構造函數必須是帶參數的。
(4)結構不支持繼承,不能結構派生其他結構。
(5)申明結構時,不允許在字段初始化時候賦值。
4.結構的編程例子
struct information
{
private string colour;
public string Colour
{
get { return colour; }
set { colour = value; }
}
private double hight;
public double Hight
{
set { hight = value; }
get { return hight; }
}
private string gender;
public string Gender
{
set { gender = value; }
get { return gender; }
}
public information(string colour, double hight, string gender)
{
//帶有參數的構造函數,必須對所有變量賦值!!
this.colour = colour;
this.gender = gender;
this.hight = hight;
}
}
class Program
{
static void Main(string[] args)
{
information info = new information("red" , 180.1 , "Man");
information info1 = info;
Console.WriteLine("colour: {0}\nhight: {1}\ngender: {2} " ,info1.Colour , info1.Hight , info1.Gender);
}
}