C#课本例题第三章

一、对象的引用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0301
{
    class Tree
    {
        internal int height;
    }
    public class Assignment
        
    {
        static void Main(string[] args)
        {
            Tree t1;
            Tree t2 = new Tree();
            Tree t3 = new Tree();
            t1 = t2;
            t2.height = 3;
            t3.height = 3;
            if (t1 == t2) Console.WriteLine("t1=t2");
            if (t2 == t3) Console.WriteLine("t2=t3");
            Console.ReadLine();
        }
    }
}

二、声明一个类的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0302
{
    class Program
    {
        static int Add(int x,int y)
        {
            return x + y;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("123+456={0}", Add(123, 456));
            Console.ReadLine();
        }
    }
}

三、方法中值参数的应用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0303
{
    class Program
    {
        static void Swap(int a, int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }
        static void Main(string[] args)
        {
            int i = 1,j = 2;
            Swap( i,j);
            Console.WriteLine("i={0};j={1}", i, j);
            Console.WriteLine( ) ;
            Console.WriteLine("Swap并没有对数据进行交换,拥有值参数的方法,不改变此方法外部的数据");
            Console.ReadLine();

        }
    }
}

四、方法中引用参数的应用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0303
{
    class Program
    {
        static void Swap(ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }
        static void Main(string[] args)
        {
            int i = 1, j = 2;
            Swap(ref i, ref j);
            Console.WriteLine("i={0};j={1}", i, j);
            Console.WriteLine();
            Console.WriteLine("Swap采用应用参数后,ij 两值调换");
            Console.ReadLine();

        }
    }
}

方法中输出参数的应用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0305
{
    class Program
    {
        static void SplitPath(string path, out string dirname, out string filename)
        {
            int n = path.Length;
            while (n > 0)
            {
                char ch = path[n - 1];
                if (ch == '\\' | ch == '/' || ch == ':') break;

                n--;
            }
                dirname = path.Substring(0, n);
                filename = path.Substring(n);
            }

            static void Main(string[] args)
            {
                string dname, fname;
                SplitPath("c:\\MyDocuments\\简历.doc", out dname, out fname);
                Console.WriteLine(dname);
                Console.WriteLine(fname);
                Console.ReadLine();

            }
        
    } }
   

六、构造函数的使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0306
{
    public class Quad
    {
        protected double width, height;
        public Quad(double d)
        {
            width = d;
            height = d;
        }
        public Quad(double w, double h)
        {
            width = w;
            height = h;
        }
        public double Area()
        {
            return width * height;
        }
    }
    public class demo
    {
 static void Main(string[] args)
        {
            Quad q1 = new Quad(4);
            Quad q2 = new Quad(2, 3);
            Console.WriteLine("q1的面积={0}", q1.Area());
            Console.WriteLine("q2的面积={0}", q2.Area());
            Console.ReadLine();

        }
    }
       
    }


七、方法的重载

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0307
{
    class Tree
    {
        int height;
        public  Tree()
        {
            Console.WriteLine("种植一棵幼苗");
             height = 0;

        }
        public Tree(int i)
        {
            Console.WriteLine("树在生长,现在高度是" + i + "尺");
            height = i;
        }
        internal void info()
        {
            Console.WriteLine("现在是" + height + "尺");
        }
        internal void info(string s)
        {
            Console.WriteLine(s + ":是" + height + "尺");
        }
    }
   public class demo
    {
        static void Main(string[] args)
        {
            new Tree();
            for(int i=0;i<4;i++)
            {
                Tree t = new Tree(i);
                t.info();
                t.info("重载方法");
            }
            Console.ReadLine();
        }
    }
}

八、继承的实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0308
{
    public class Parent
    {
        string parentString;

        public Parent()
        {
            Console.WriteLine("父体类");
        }
        public Parent(string myString)
        {
            parentString = myString;
            Console.WriteLine(parentString);
        }
        public void Print()
        {
            Console.WriteLine("这里是父类");
        }
    }
    public class Child : Parent
    {
        public Child()
            : base("从父类")
        {
            Console.WriteLine("子体类");
        }
        public void Print()
        {
            base.Print();
            Console.WriteLine("这里是子类");
        }


        static void Main(string[] args)
        {
            Child child = new Child();
            child.Print();
            ((Parent)child).Print();
            Console.ReadLine();
        }
    }
}
    


九、覆盖的应用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0309
{
    class Car
    {
        public int wheels;
        protected float weight;
        public Car()
        {
            ;
        }
        public Car(int w, float g)
        {
            wheels = w;
            weight = g;
        }
        public void speak()
        {
            Console.WriteLine("Car Balabala");
        } 
    }
    class auto:Car
    {
        int passenagers;
        public auto(int w,float g,int p)
            :base(w,g)
        {
            wheels = w;
            weight=g;
            passenagers = p;
        }
        new public void speak()
        {
            Console.WriteLine("bibi");

        }
        static void Main(string[] args)
        {
            auto car = new auto(10, 10, 20);
            car.speak();
            Console.ReadLine();
        }
        
    }
        
    }


十、多态的应用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0310
{
    public class Rectangle
    {
        protected double a, b;
        public Rectangle() { }
        public Rectangle(double a, double b)
        {
            this.a = a;
            this.b = b;
        }
        public virtual double Area()
        {
            return a * b;
        }
    }
    public class Cylinder : Rectangle
    {
        public Cylinder(double h, double r):base(h,r) { }
        public override double Area()
        {
            return 2 * Math.PI * b * b + 2 * Math.PI * a * b;
        }
    }
    public class Test
    { 
        static void Main(string[] args)
    {
            Rectangle r = new Rectangle(1, 10);
            Cylinder c = new Cylinder(4, 2);
            Console.WriteLine("矩形的面积:{0}", r.Area());
            Console.WriteLine("圆柱体的表面积:{0}", c.Area());
            Console.ReadLine();
    }
}
}

十一、域的应用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0311
{
    public class FieldTest
    {
        public static int n = 1;
        public int m = 1;
        public FieldTest()
        {
            n++;
            m++;
        }
    }
    class ex0309
    { 
        static void Main(string[] args)
        {
            Console.WriteLine(FieldTest.n);
            FieldTest t1=new FieldTest();
            Console.WriteLine(FieldTest.n);
            Console.WriteLine(t1.m);
            FieldTest t2 = new FieldTest();
            Console.WriteLine(FieldTest.n);
            Console.WriteLine(t2.m);
            Console.ReadLine();
        }
    }
}

十二、属性的应用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0312
{
    public class Employee
    {
        private string name;
        private long idcard;
        private double salary;
        private double increase;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public double Salary
        {
            get { return salary; }
            set { salary = value; }
        }
        public long ID
        {
            get { return idcard; }
            set { idcard = value; }
        }
        public void Print()
        {
            Console.WriteLine("姓名:{0}", name);
            Console.WriteLine("ID:{0}", idcard);
            Console.WriteLine("工资:{0}", salary);
            Console.WriteLine("加薪:{0}",increase);
        }

        public void raise(double percent)
        {
            increase = percent * salary;
        }
        public Employee(string n,long id,double s)
        {
            name = n;
            idcard = id;
            salary = s;
        }
    }
    public class PropertyTest
    {
        static void Main(string[] args)
        {
            Employee e = new Employee("张三", 1000001, 2000.0);
            e.raise(0.07);
            e.Print();
            e.Name = "李四";
            e.Salary = 6000.0;
            e.raise(0.05);
            Console.WriteLine(e.Name);
            e.Print();
            Console.ReadLine();

        }
    }
}

十三、设计一个“三角形”类,其中包括公共数据域三个顶点坐标,判断是否为三角形,并求解其面积

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0313
{
    class SJX
    {
        public int Px1, Px2, Px3, PY1, PY2, PY3;
        public bool IsSJX()
        {
            if ((PY3 - PY2) * (Px3 - Px1) == (PY3 - PY1) * (Px3 - Px2))
                return false;
            else
                return true;
        }
        public double Mj()
        {
            return Math.Abs(Px1 * PY2 + Px2 * PY3 + Px3 * PY1 - PY1 * Px2 - PY2 * Px3 - PY3 * Px1) / 2.0;
        }
        static void Main(string[] args)
        {
            SJX sjx = new SJX();
            Console.Write("请输入第1点X: ");sjx.Px1 = Convert.ToInt16(Console.ReadLine());
            Console.Write("请输入第2点X: "); sjx.Px2 = Convert.ToInt16(Console.ReadLine());
            Console.Write("请输入第3点X: "); sjx.Px3 = Convert.ToInt16(Console.ReadLine());
            Console.Write("请输入第1点Y: "); sjx.PY1 = Convert.ToInt16(Console.ReadLine());
            Console.Write("请输入第2点Y: "); sjx.PY2 = Convert.ToInt16(Console.ReadLine());
            Console.Write("请输入第3点Y: "); sjx.PY3 = Convert.ToInt16(Console.ReadLine());
            if (sjx.IsSJX())
            {
                Console.WriteLine("该△面积={0}", sjx.Mj());
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("该点不能构成三角形");
                Console.ReadLine();
            }

        }
    }
    
}

继续十三,定义一个类DYSJX(等腰三角形),继承SJX类,判断是否为等腰三角形,并求其面积。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ex0314
{
    class SJX
    {
        public int Px1, Px2, Px3, PY1, PY2, PY3;
        public bool IsSJX()
        {
            if ((PY3 - PY2) * (Px3 - Px1) == (PY3 - PY1) * (Px3 - Px2))
                return false;
            else
                return true;
        }
        public double Mj()
        {
            return Math.Abs(Px1 * PY2 + Px2 * PY3 + Px3 * PY1 - PY1 * Px2 - PY2 * Px3 - PY3 * Px1) / 2.0;
        }
    }
    class DYSJX : SJX
    {
        public bool IsDYSJX()
        {
            double l1, l2, l3;
            l1=Math.Sqrt(Math.Abs((Px1-Px2)*(Px1-Px2)-(PY1-PY2)*(PY1-PY2)));
            l2 = Math.Sqrt(Math.Abs((Px1 - Px3) * (Px1 - Px3) - (PY1 - PY3) * (PY1 - PY3)));
            l3 = Math.Sqrt(Math.Abs((Px3 - Px2) * (Px3 - Px2) - (PY3 - PY2) * (PY3 - PY2)));
            if ((l1 == l2) || (l2 == l3) || (l1 == l3))
                return true;
            else
                return false;
        }
    }
    class Program
    { 
        static void Main(string[] args)
        {
            DYSJX dysjx = new DYSJX();
            Console.Write("请输入第1点X: "); dysjx.Px1 = Convert.ToInt16(Console.ReadLine());
            Console.Write("请输入第2点X: "); dysjx.Px2 = Convert.ToInt16(Console.ReadLine());
            Console.Write("请输入第3点X: "); dysjx.Px3 = Convert.ToInt16(Console.ReadLine());
            Console.Write("请输入第1点Y: "); dysjx.PY1 = Convert.ToInt16(Console.ReadLine());
            Console.Write("请输入第2点Y: "); dysjx.PY2 = Convert.ToInt16(Console.ReadLine());
            Console.Write("请输入第3点Y: "); dysjx.PY3 = Convert.ToInt16(Console.ReadLine());
            if (dysjx.IsSJX())
            {
                Console.WriteLine("该△面积={0}", dysjx.Mj());
                if (dysjx.IsDYSJX())
                    Console.WriteLine("是等腰三角形");
                else
                    Console.WriteLine("不是等腰三角形");

                    Console.ReadLine();
            }
            else
            {
                Console.WriteLine("该点不能构成三角形");
                Console.ReadLine();
            }

        }
    }

}

给初学者的简单例题! private System.ComponentModel.IContainer components; private const int kNumberOfRows = 8; private const int kNumberOfTries = 3; private int NumTotalBricks = 0; private int NumBalls = 0; private Ball TheBall = new Ball(); private Paddle ThePaddle = new Paddle(); private System.Windows.Forms.Timer timer1; private Row[] Rows = new Row[kNumberOfRows]; private Score TheScore = null; private Thread oThread = null; [DllImport("winmm.dll")] public static extern long PlaySound(String lpszName, long hModule, long dwFlags); public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); for (int i = 0; i < kNumberOfRows; i++) { Rows[i] = new Row(i); } ThePaddle.Position.X = 5; ThePaddle.Position.Y = this.ClientRectangle.Bottom - ThePaddle.Height; TheBall.Position.Y = this.ClientRectangle.Bottom - 200; this.SetBounds(this.Left, this.Top, Rows[0].GetBounds().Width, this.Height); TheScore = new Score(ClientRectangle.Right - 50, ClientRectangle.Bottom - 180); // choose Level SpeedDialog dlg = new SpeedDialog(); if (dlg.ShowDialog() == DialogResult.OK) { timer1.Interval = dlg.Speed; } // // TODO: Add any constructor code after InitializeComponent call // } /// /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } private string m_strCurrentSoundFile = "BallOut.wav"; public void PlayASound() { if (m_strCurrentSoundFile.Length > 0) { PlaySound(Application.StartupPath + "\\" + m_strCurrentSoundFile, 0, 0); } m_strCurrentSoundFile = ""; oThread.Abort(); } public void PlaySoundInThread(string wavefile) { m_strCurrentSoundFile = wavefile; oThread = new Thread(new ThreadStart(PlayASound)); oThread.Start(); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.timer1 = new System.Windows.Forms.Timer(this.components); // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(552, 389); this.KeyPreview = true; this.Name = "Form1"; this.Text = "Brick Out"; this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown); this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint); } #endregion /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; g.FillRectangle(Brushes.White, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height); TheScore.Draw(g); ThePaddle.Draw(g); DrawRows(g); TheBall.Draw(g); } private void DrawRows(Graphics g) { for (int i = 0; i < kNumberOfRows; i++) { Rows[i].Draw(g); } } private void CheckForCollision() { if (TheBall.Position.X < 0) // hit the left side, switch polarity { TheBall.XStep *= -1; TheBall.Position.X += TheBall.XStep; PlaySoundInThread("WallHit.wav"); } if (TheBall.Position.Y this.ClientRectangle.Right - TheBall.Width ) // hit the left side, switch polarity { TheBall.XStep *= -1; TheBall.Position.X += TheBall.XStep; PlaySoundInThread("WallHit.wav"); } if (TheBall.Position.Y > this.ClientRectangle.Bottom - TheBall.YStep) // lost the ball! { IncrementGameBalls(); Reset(); PlaySoundInThread("BallOut.wav"); } if (RowsCollide(TheBall.Position)) { TheBall.YStep *= -1; PlaySoundInThread("BrickHit.wav"); } int hp = HitsPaddle(TheBall.Position); if (hp > -1)// lost the ball! { PlaySoundInThread("PaddleHit.wav"); switch (hp) { case 1: TheBall.XStep = -7; TheBall.YStep = -3; break; case 2: TheBall.XStep = -5; TheBall.YStep = -5; break; case 3: TheBall.XStep = 5; TheBall.YStep = -5; break; default: TheBall.XStep = 7; TheBall.YStep = -3; break; } } } private int HitsPaddle(Point p) { Rectangle PaddleRect = ThePaddle.GetBounds(); if (p.Y >= this.ClientRectangle.Bottom - (PaddleRect.Height + TheBall.Height) ) { if ((p.X > PaddleRect.Left) && (p.X PaddleRect.Left) && (p.X PaddleRect.Left + PaddleRect.Width/4) && (p.X PaddleRect.Left + PaddleRect.Width/2) && (p.X = kNumberOfTries) { timer1.Stop(); string msg = "Game Over\nYou knocked out " + NumTotalBricks; if (NumTotalBricks == 1) msg += " brick."; else msg += " bricks."; MessageBox.Show(msg); Application.Exit(); } } private void Reset() { TheBall.XStep = 5; TheBall.YStep = 5; TheBall.Position.Y = this.ClientRectangle.Bottom - 190; TheBall.Position.X = 5; timer1.Stop(); TheBall.UpdateBounds(); Invalidate(TheBall.GetBounds()); } private int SumBricks () { int sum = 0; for (int i = 0; i < kNumberOfRows; i++) { sum += Rows[i].BrickOut; } return sum; } private bool RowsCollide (Point p) { for (int i = 0; i < kNumberOfRows; i++) { if (Rows[i].Collides(TheBall.GetBounds())) { Rectangle rRow = Rows[i].GetBounds(); Invalidate(rRow); return true; } } return false; } private void timer1_Tick(object sender, System.EventArgs e) { TheBall.UpdateBounds(); Invalidate(TheBall.GetBounds()); TheBall.Move(); TheBall.UpdateBounds(); Invalidate(TheBall.GetBounds()); CheckForCollision(); NumTotalBricks = SumBricks(); TheScore.Count = NumTotalBricks; Invalidate(TheScore.GetFrame()); if (NumTotalBricks == kNumberOfRows*Row.kNumberOfBricks) { timer1.Stop(); MessageBox.Show("You Win! You knocked out all the bricks!"); Application.Exit(); } } private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { string result = e.KeyData.ToString(); Invalidate(ThePaddle.GetBounds()); switch (result) { case "Left": ThePaddle.MoveLeft(); Invalidate(ThePaddle.GetBounds()); if (timer1.Enabled == false) timer1.Start(); break; case "Right": ThePaddle.MoveRight(ClientRectangle.Right); Invalidate(ThePaddle.GetBounds()); if (timer1.Enabled == false) timer1.Start(); break; default: break; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值