using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calculator_Demo.Class_Folder { public abstract class Calculator { public double Number1 { get; set; } public double Number2 { get; set; } public Calculator(double a, double b) { this.Number1 = a; this.Number2 = b; } /// <summary> /// 计算 /// </summary> /// <returns></returns> public abstract double calculate(); } /// <summary> /// 加 /// </summary> public class addCalculator : Calculator { public addCalculator(double a, double b): base(a, b) { } /// <summary> /// 重写父类的calculate方法 /// </summary> /// <returns></returns> public override double calculate() { return Number1 + Number2; } } /// <summary> /// 减 /// </summary> public class minusCalculator : Calculator { public minusCalculator(double a, double b) : base(a, b) { } public override double calculate() { return Number1 - Number2; } } /// <summary> /// 乘 /// </summary> public class multiplyCalculator : Calculator { public multiplyCalculator(double a, double b) : base(a, b) { } public override double calculate() { return Number1 * Number2; } } /// <summary> /// 除 /// </summary> public class DivideCalculator : Calculator { public DivideCalculator(double a, double b) : base(a, b) { } public override double calculate() { return Number1 / Number2; } } }
这个怎么写成泛型的?
这个加减乘除适用的类型不是很多,没必要啊
就是想看看怎么引入泛型,发现写不出...
@Cgrain:
public abstract class Calculator<T>
{
public T Number1 { get; set; }
public T Number2 { get; set; }
public Calculator(T a, T b)
{
this.Number1 = a;
this.Number2 = b;
}
/// <summary>
/// 计算
/// </summary>
/// <returns></returns>
public abstract double calculate();
}
/// <summary>
/// 加
/// </summary>
public class addCalculator<T> : Calculator<T>
{
public addCalculator(T a, T b)
: base(a, b)
{
}
/// <summary>
/// 重写父类的calculate方法
/// </summary>
/// <returns></returns>
public override double calculate()
{
double tmp;
if (double.TryParse(Number1.ToString(), out tmp) && double.TryParse(Number2.ToString(), out tmp))
return double.Parse(Number1.ToString()) + double.Parse(Number2.ToString());
else return 0;
}
}
是这样的吗?
@华临天下: 你前面这个我看懂了,但是你这个重写父类的方法我没看懂...
@Cgrain:
if (double.TryParse(Number1.ToString(), out tmp) && double.TryParse(Number2.ToString(), out tmp))
return double.Parse(Number1.ToString()) + double.Parse(Number2.ToString());
else return 0;
这边没看懂吗?这边主要是判断这个能不能转成double类型,不然你怎么加减乘除
@华临天下: .. 咋不用这个 Convert.ToDouble()
@Cgrain: 转换类型都可以,看你习惯哪个就好
@华临天下: 了解了
没有泛型约束适用于强制运算符重载的,因此这类需要支持基本运算符的泛型总是不安全的。关于这类泛型的建议见这里。使用泛型重构加法运算的代码如下,另外,注意C#的编码规范,类与方法需要使用Pascal命名法:
public abstract class Calculator<T>
{
public T Number1 { get; set; }
public T Number2 { get; set; }
protected Calculator(T a, T b)
{
this.Number1 = a;
this.Number2 = b;
}
public abstract T Calculate();
}
public class AddCalculator<T> : Calculator<T>
{
public AddCalculator(T a, T b) : base(a, b){}
public override T Calculate()
{
dynamic n1 = Number1;
dynamic n2 = Number2;
return n1 + n2;
}
}
提取泛型,入参最好能有泛型约束,但是加减乘除好像没有泛型约束