1.面向对象的3大属性,封装、继承、多态,以一个加单的计算机为例:
创建一个父类Operation 有两个属性 和一个计算方法(虚方法),便于子类重写:
public class Operation
{
private double _numberA = 0;
private double _numberB = 0; public double NumberA
{
get { return _numberA; }
set { _numberA = value; }
} public double NumberB
{
get { return _numberB; }
set { _numberB = value; }
} /// <summary>虚方法
///
/// </summary>
/// <returns></returns>
public virtual double GetResult()
{
double result = 0;
return result;
}
}
接下来创建计算类,加减乘除类来集成操作类
加类
public class OperationAdd:Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
减类
public class OperationSub:Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
乘类
public class OperationMul:Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA * NumberB;
return result;
}
}
除类
public class OperationDiv:Operation
{
public override double GetResult()
{
double result = 0;
if (NumberB == 0)
throw new Exception("除数不能为0");
result = NumberA / NumberB;
return result;
}
}
然后通过简单工厂类来创建计算的实例
public class OperationFactory
{
public static Operation createOperate(string operate)
{
Operation oper = null;
switch (operate)
{
case "+":
oper = new OperationAdd();
break;
case "-":
oper = new OperationSub();
break;
case "*":
oper = new OperationMul();
break;
case "/":
oper = new OperationDiv();
break;
}
return oper;
}
}
最后通过界面去调用:
static void Main(string[] args)
{
Operation oper;
oper = OperationFactory.createOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
Console.WriteLine(result);
Console.ReadKey();
}
这里把计算过程都封装成一个方法,每个计算类又集成了操作类,这样由于每个方法都重写了计算方法,这里表现出一个方法的不同表现形态,如果以后要增加其他的方法,只需要继承操作类 重写计算方法即可,这样也不会对原有的程序进行修改,实现了解耦,面向对象语言的优点在于可维护性,可复用,可扩展、灵活性。
以上为自学的一点总结,希望有不对的地方,请大家指点,谢谢