虚方法,重写————继承、多态、面向对象!
1、 this 不能直接调用 非static成员
class A
{
static public void M1()
{
Hello(); // 错误 在static成员中不能
直接调用非static成员
A a=new A();
a.Hello();
}
public void Hello()
{
F1 =10;
M1();
A.M1();
this.M1() //错误 不能调用
}
}
2、 静态类不能new;
静态类中不能声明非静态成员。
3、sealed 密闭类不能被继承
Fromwork
4、Paint 重绘控件
private void panel1_Paint(object
sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
// g.Dispose();
}
重绘控件 不用释放。
5、画一个圆
g.DrawEllipse(Pens.Blue, 20, 50, 60, 80);
//椭圆 (边框颜色,左上角坐标(20,50
),宽度为60,高为80);
g.DrawRectangle(Pens.Blue, 20, 50, 60,
80);
6、int.Parse()与int.TryParse()
int i = -1;
bool b = int.TryParse(null, out i);
执行完毕后,b等于false,i等于0,而不是等于-1
,切记。
int i = -1;
bool b = int.TryParse("123", out i);
执行完毕后,b等于true,i等于123;
7、virtual 虚方法 与override(重写) 连用
class A
{
public virtual void M1()
{ }
}
class B:A
{
public override void M1()
{
Console.WriteLine("213");
}
}
Virtual关键字表示方法,使用Virtual关键字修
饰的方法,必须有实现{},子类可以重写
(override),也可以不重写。
注:方法重写时,方法签名必须与父类中的虚方法
完全一致,否则重写不成功,其中包括“返回值”
8、多态实例(面向对象) virtual , override
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleApplication1 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 Console.WriteLine("请输入姓名"); 13 Person p = new Person(); 14 p.Name = Console.ReadLine(); 15 Console.WriteLine("请输入性别"); 16 p.Sex = Console.ReadLine(); 17 PersonBase pb = null; 18 if (p.Sex == "1") 19 { 20 pb = new Man(p); 21 } 22 else { 23 pb = new Woman(p); 24 } 25 pb.Show(); 26 //Console.WriteLine(); 27 Console.ReadLine(); 28 } 29 } 30 31 class Person 32 { 33 public string Name { get; set; } 34 public string Age { get; set; } 35 public string Sex { get; set; } 36 37 } 38 39 class PersonBase 40 { 41 protected string Name; 42 public PersonBase(Person model) 43 { 44 this.Name = model.Name; 45 } 46 public virtual void Show() 47 { 48 Console.WriteLine(string.Format("{0}是人",Name)); 49 } 50 } 51 52 class Man:PersonBase 53 { 54 public Man(Person model):base(model) { } 55 public override void Show() 56 { 57 Console.WriteLine(string.Format("{0}是男人", Name)); 58 } 59 } 60 61 class Woman : PersonBase 62 { 63 public Woman(Person model):base(model) { } 64 public override void Show() 65 { 66 Console.WriteLine(string.Format("{0}是女人", Name)); 67 } 68 } 69 }
浙公网安备 33010602011771号