一:
using System;
//多态:同一个行为,多个不同的表现形式或形态的能力
namespace 第二周_类的多态
{
public class polymorphic
{ //重载
public int Add(int a,int b,int c)
{
return a + b + c;
}
public int Add(int a,int b)
{
return a + b;
}
public void Print(int i)
{
Console.WriteLine("输出整数:" + i);
}
public void Print(double f)
{
Console.WriteLine("输出双精度数:" + f);
}
public void Print(string str)
{
Console.WriteLine("输入字符串:" + str);
}
}
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello World!");
polymorphic pol = new polymorphic();
int a= pol.Add(1, 2);
int b=pol.Add(1, 2, 3);
Console.WriteLine(a);
Console.WriteLine(a);
pol.Print(1);
pol.Print(1.5f);//隐式转换,转到double
pol.Print(" string");//+2个重载,其实是3个
}
}
}
二:
using System;
namespace 第二周_类的多态1
{
//抽象类
/// <summary>
/// 代码风格,规矩一点
/// </summary>
public abstract class shape
{
public abstract int GetArea();//理解为方法的声明,实现在后面
};
public class Normal
{
public int Test() { return 0; }
}
public class Rect:shape//如果继承自抽象类中的抽象函数必须实现
{
private int len;
private int width;
public Rect(int a=0,int b=0)
{
len = a;
width = b;
}
public override int GetArea()//重载
{
Console.WriteLine("计算矩形的面积:");
return len * width;
//throw new NotImplementedException();
}
}
// abstract class shape01
//{ };//可以这么写,因为默认的是public
class Program
{
static void Main(string[] args)
{
Rect rect = new Rect(2,4);
int a = rect.GetArea();
Console.WriteLine(a);
//Console.WriteLine("Hello World!");
}
}
}
原文:https://www.cnblogs.com/Nicela/p/13130039.html