C#多态及接口

直接看代码吧

using System;
using static System.Console; namespace ConsoleApp
{
//使用abstract,抽象类或方法,不能使用virtual,派生类必须实现所有抽象方法
abstract class Shape
{
public int Size { get; set; } public virtual void Draw()
{
WriteLine("shap");
}
}
//密封类(方法),就不能派生(重写) string类为密封的
sealed class Rect: Shape
{
public override void Draw()
{
WriteLine("rect");
//base.Draw();
}
}
//接口 相当于抽象类
//不能声明成员的修饰符,成员总是public,不能声明为virtual
//接口也可以彼此继承,从而添加新的声明
public interface IMyInterface
{
//可以包含方法、属性、索引器和事件的声明,不能实现
void Draw();
int Size { get; set; } }
//继承接口的类必须实现接口的所有东西
class A : IMyInterface
{
public void Draw()
{
WriteLine('A');
}
private int _size;
public int Size
{
get
{
return _size;
}
set
{
_size = value;
}
}
} class B : IMyInterface
{
public void Draw()
{
WriteLine('B');
}
private int _size;
public int Size
{
get
{
return _size;
}
set
{
_size = value;
}
}
} class Program
{
public void as_is(object o)
{
//1 ,如果该object类型不对就会引发InvalidCastException异常
IMyInterface myinterface = (IMyInterface)o;
myinterface.Draw(); //2 as
IMyInterface myinterface1 = o as IMyInterface;
if (myinterface1 != null)
{
myinterface1.Draw();
} //3 is
if (o is IMyInterface)
{
IMyInterface myinterface2 = (IMyInterface)o;
myinterface2.Draw();
} } static void Main(string[] args)
{
Shape s = new Rect();
s.Draw(); //接口可以引用任何实现该接口的类
IMyInterface a = new A();
IMyInterface b = new B(); a.Draw();
b.Draw(); }
}
}
上一篇:Foundation框架中日期的操作


下一篇:Vue.js最简单的代码