结构体:相当于是我们自己定义的一种复杂的类型。 int... double float bool char string DateTime 数组类型 生活中大部份的对象都是复合型的对象。
如何定义结构体类型? 一般来说结构体的定义要放在class的外面或class的里面,尽量不放在Main的里面。 struct 自定义类型名 { public 变量类型 变量名; ......; ......; ......;
} 例如: struct YuanGong //自定义的数据类型。用来描述员工的信息。 { public string NO; public string Name; public int Age; public string Nation; public bool Sex; }
如何用自定义的类型来定义变量? 自定义类型名 变量 = new 自定义类型名();
如何使用自定义类型的变量? 变量.子变量 = "xxxx"; Console.WriteLine(变量名.子变量); 例如: //定义自定义类型的变量 YuanGong zhangsan = new YuanGong(); //给变量赋值 zhangsan.NO = "Y001"; zhangsan.Name = "张三"; zhangsan.Age = 22; zhangsan.Sex = true; zhangsan.Nation = "汉族"; //对变量取值 Console.WriteLine(zhangsan.NO+" "+zhangsan.Name+" "+zhangsan.Age); Console.WriteLine(zhangsan.Nation+" "+(zhangsan.Sex?"男":"女"));
对战游戏
struct Ren { public string Name; public int Blood; public int Attack; public int Defend;
} class Class4 { static void Main(string[] args) { Ren r1=new Ren(); Ren r2=new Ren(); Console .Write ("请第一个高手出场:"); r1.Name =Console .ReadLine (); Console .Write ("请第二个高手出场:"); r2.Name =Console .ReadLine (); //生成血量 Random rand=new Random (); r1.Blood =rand.Next (1000)+1000; r2.Blood =rand.Next (1000)+1000; //攻防 r1.Attack = rand.Next(50)+50; r2.Attack = rand.Next(50) + 50; r1.Defend = rand.Next(50)+50; r2.Defend = rand.Next(50) + 50; Console .WriteLine ("大侠"+r1.Name +" ,生命力"+r1.Blood ); Console .WriteLine ("大侠"+r2.Name +" ,生命力"+r2.Blood ); Console .WriteLine ("在一个月黑风高的夜晚狭路相逢!");
while (true) { //跳出循环 if(r1.Blood <=0&&r2.Blood <=0) { Console .WriteLine (r1.Name +"与"+r2.Name+"皆倾尽全力,共赴黄泉" ); break; } if(r1.Blood <=0) { Console .WriteLine (r2.Name +"用了一记猴子捞月,结束了"+r1.Name +"的生命"); break; } if(r2.Blood <=0) { Console .WriteLine (r1.Name +"用了一记黑虎掏心,结束了"+r2.Name +"的生命"); break; } //对战 int b1=rand.Next (200);//r1掉的血 r1.Blood -=b1; if(r1.Blood <0) { r1.Blood =0; } System.Threading.Thread.Sleep(1000); Console.ForegroundColor = ConsoleColor.Red; Console .WriteLine (r2.Name +"抡起拳头打了"+r1.Name+b1+"点血"); Console.ResetColor(); Console.WriteLine(); //稍等一下 System.Threading.Thread.Sleep(1500); int b2=rand.Next (200);//r2掉的血
r2.Blood -=b2; if(r2.Blood <0) { r2.Blood =0; } Console.ForegroundColor = ConsoleColor.DarkCyan; Console .WriteLine (r1.Name +"抡起拳头打了"+r2.Name+b2+"点血"); Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Yellow; Console .WriteLine("大侠"+r1.Name +"还有"+r1.Blood +"生命力!"); Console .Write("大侠"+r2.Name +"还有"+r2.Blood +"生命力!"); Console.ResetColor(); Console.WriteLine(); Console.WriteLine();
}
} }