源码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CalOprs co = new CalOprs();
co.GetOpr("3+2");
co.GetOpr("3*2");
co.GetOpr("3-2");
co.GetOpr("3/2");
}
}
interface Icalt
{
double CalResult();
}
class Cal : Icalt
{
private double op1;
private double op2;
public double Op1
{
get {
return op1;
}
set {
op1 = value;
}
}
public double Op2
{
get
{
return op2;
}
set
{
op2 = value;
}
}
public Cal() {
this.op1 = 0;
this.op2 = 0;
}
public Cal(double op1, double op2)
{
this.op1 = op1;
this.op2 = op2;
}
public virtual double CalResult()
{
return 0;
}
}
class CalAdd : Cal {
public CalAdd() : base()
{
}
public CalAdd(double op1, double op2) :base(op1,op2)
{
}
public override double CalResult()
{
return this.Op1 + this.Op2;
}
}
class CalSub : Cal
{
public CalSub()
: base()
{
}
public CalSub(double op1, double op2)
: base(op1, op2)
{
}
public override double CalResult()
{
return this.Op1 - this.Op2;
}
}
class CalMul : Cal
{
public CalMul()
: base()
{
}
public CalMul(double op1, double op2)
: base(op1, op2)
{
}
public override double CalResult()
{
return this.Op1 * this.Op2;
}
}
class CalDiv : Cal
{
public CalDiv()
: base()
{
}
public CalDiv(double op1, double op2)
: base(op1, op2)
{
}
public override double CalResult()
{
return this.Op1 / this.Op2;
}
}
class CalOprs {
public Cal GetOpr(string s) {
int i=0;
char op=' ';
for (; i < s.Length; i++)
{
if (!(s.ElementAt(i) >= '0' && s.ElementAt(i) <= '9'))
op = s.ElementAt(i);
}
Cal ca = new Cal();
ca.Op1 = double.Parse(s.Split(op)[0]);
ca.Op2 = double.Parse(s.Split(op)[1]);
switch (op) {
case '+':
CalAdd caa = new CalAdd(ca.Op1, ca.Op2);
Console.WriteLine("{0}",caa.CalResult());
break;
case '-':
CalSub cas = new CalSub(ca.Op1, ca.Op2);
Console.WriteLine("{0}", cas.CalResult());
break;
case '*':
CalMul cam = new CalMul(ca.Op1, ca.Op2);
Console.WriteLine("{0}", cam.CalResult());
break;
case '/':
CalDiv cad = new CalDiv(ca.Op1, ca.Op2);
Console.WriteLine("{0}", cad.CalResult());
break;
}
return ca;
}
}
}