C#4.0 通过dynamic实现多态

之前在C#中能够体现多态的地方有重写,重载,显式接口,现在发现用dynamic也可以实现多态:

using System;

namespace PractiseDynamic

{

class Program

{

static void Main(string[] args)

{

DynamicClass theClass = new DynamicClass();

theClass.DynamicMethod(new MyClass1());

theClass.DynamicMethod(new MyClass2());

Console.ReadKey();

}

}

class DynamicClass

{

public void DynamicMethod(dynamic instanceClass)

{

instanceClass.Method();

}

}

class MyClass1

{

public void Method()

{

Console.WriteLine("I'm the instance of MyClass1");

}

}

class MyClass2

{

public void Method()

{

Console.WriteLine("I'm the instance of MyClass2");

}

}

}

你可能感兴趣的:(dynamic)