类的几个重要特性之一多态性,有着广泛的用途。
类的多态性包括:编译时多态和运行时多态。
编译时多态表现为一个同名的方法会根据参数类型、个数和位置的不同有不同执行效果。通过方法重载来实现。顾名思义,它由编译器根据调用参数的不同,选择相应的函数。
运行时多态通过虚方法实现。表现为:相同的参数,仍会执行不同的函数。
例如:
//using System;
//using System.Collections.Generic;
//using System.Collections;
//using System.Text;
//namespace study
//{
// class Program
// {
// static void Main(string[] args)
// {
// ArrayList a = new ArrayList();
// A tmp;
// a.Add(new A(1,"a"));
// a.Add(new A(3,"b"));
// a.Add(new A(1,"c"));
// a.Add(new A(2, "a"));
// a.Add(new A(1, "b"));
// a.Add(new A(3, "c"));
// a.Sort(new ItypeCompare());
// int i;
// for (i = 0; i < a.Count; i++)
// {
// tmp = (A)a[i];
// Console.WriteLine("{0}:{1}", tmp.Type1, tmp.Type2);
// }
// Console.ReadLine();
// }
// }
// public class ItypeCompare : System.Collections.IComparer
// {
// public int Compare(object x, object y)
// {
// A t1, t2;
// t1 = (A)x;
// t2 = (A)y;
// if (t1.Type1 == t2.Type1)
// {
// return string.Compare(t1.Type2, t2.Type2);
// }
// else
// {
// return t1.Type1 - t2.Type1;
// }
// }
// }
// class A
// {
// private int m_type1;
// private string m_type2;
// public int Type1 { get{return m_type1;}
// set{this.m_type1=value;}
// }
// public string Type2 { get { return this.m_type2;} set {this.m_type2=value ;} }
// public A(int arg1, string arg2)
// {
// this.m_type1 = arg1;
// this.m_type2 = arg2;
// }
// }
//}
//using System;
//using System.Collections.Generic;
//using System.Collections;
//using System.Text;
//namespace study
//{
// class Program
// {
// static void Main(string[] args)
// {
// int i=1;
// int j = new int();
// System.Console.WriteLine("{0},{1}", i, j);
// Console.ReadLine();
// }
// }
//}
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace study
{
class Program
{
static void fun3(A x)
{
x.fun1();
x.fun2();
}
static void Main(string[] args)
{
A a1 = new A();
B b = new B();
A a2 = b; //基类引用子类
a1.fun1();
a1.fun2();
b.fun1();
b.fun2();
a2.fun1();
a2.fun2();
fun3(a1);
fun3(b);
Console.ReadLine();
}
}
class A
{
public void fun1() { Console.WriteLine("A.fun1()"); }
public virtual void fun2(){Console.WriteLine("A.fun2()");}//vitual必须位于函数返回值类型之前
}
class B:A
{
public new void fun1() { Console.WriteLine("B.fun1()"); }
public override void fun2() { Console.WriteLine("B.fun2()"); }//vitual必须位于函数返回值类型之前
}
}///请分析下结果 :)
输出的结果:
A.fun1()
A.fun2()
B.fun1()
B.fun2()
A.fun1()
B.fun2()
A.fun1()
A.fun2()
A.fun1()
B.fun2()
对于fun3函数,参数相同,却因为A所引用的对象不同,调用不同的函数。首发:http://xujiayou.w66.mydnns.cn/post/9.html