这段代码如何改成泛型？

0

```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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 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;
}
}

}```

0

这个加减乘除适用的类型不是很多，没必要啊

@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>
{
: 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;

@华临天下: ..  咋不用这个 Convert.ToDouble()

@Cgrain: 转换类型都可以，看你习惯哪个就好

@华临天下: 了解了

0

``````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 AddCalculator(T a, T b) : base(a, b){}

public override T Calculate()
{
dynamic n1 = Number1;
dynamic n2 = Number2;
return n1 + n2;
}
}``````

0

https://www.cnblogs.com/hhzblogs/p/7820005.html

0

Not丶see | 园豆：349 (菜鸟二级) | 2019-10-12 11:24

您需要登录以后才能回答，未注册用户请先注册