怎么来理解c#多态性,举个简单的例子吧
2016-12-26
展开全部
面向对象的三大特性:封装、继承、多态。
多态的定义:同一消息可以根据发送对象的不同而采用多种不同的行为方式。
多态的作用:消除类型之间的耦合关系。
实例:
public abstract class Operation
{
public abstract decimal GetResult(decimal va, decimal vb);
}
public class OperationAdd : Operation
{
public override decimal GetResult(decimal va, decimal vb)
{
return va + vb;
}
}
public class OperationSub : Operation
{
public override decimal GetResult(decimal va, decimal vb)
{
return va - vb;
}
}
public class OperationMul : Operation
{
public override decimal GetResult(decimal va, decimal vb)
{
return va * vb;
}
}
public class OperationDiv : Operation
{
public override decimal GetResult(decimal va, decimal vb)
{
return va / vb;
}
}
public static class OperationFactory
{
public static Operation Create(string operate)
{
switch (operate)
{
case "+":
return new OperationAdd();
case "-":
return new OperationSub();
case "*":
return new OperationMul();
case "/":
return new OperationDiv();
default:
throw new ArgumentException("Unknown operator");
}
}
}
static void Main(string[] args)
{
var operation = OperationFactory.Create("-");
var result = operation.GetResult(34, 9);
Console.WriteLine(result.ToString());
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询