使用继承并修改某些函数中的参数

时间:2011-08-07 18:20:29

标签: c# oop

我需要创建数学问题。算术,比较2个数字..每个类都包含类似CheckTheAnswer和GenerateProblem的类似功能,但每个类都接收不同的参数。这是我正在尝试做的一个例子。

public class Problem<T>
{
    public virtual bool CheckTheAnswer()
    {
        return false;
    }

    public static T GenerateProblem()
    {
        return T;
    }
}

public class Arithmetic : Problem<Arithmetic>
{
    public bool CheckTheAnswer(decimal result)
    {
        ...
    }

    public static Arithmetic GenerateProblem(Tuple<int, decimal, decimal> condition)
    {
        ...
    }
}

public class Comparison2Numbers : Problem<Comparison2Numbers>
{
    public bool CheckTheAnswer(decimal result1, decimal result2)
    {
        ...
    }

    public static Comparison2Numbers GenerateProblem(Tuple<decimal, decimal> condition)
    {
        ...
    }
}

我在接口中思考,但我意识到在接口中不能有静态功能。 提前谢谢。

好的,问题是..有没有办法做到这一点?

Arithmetic a = new Arithmetic();
Problem<Arithmetic> p = a;

从Arithmetic类中获取函数。也许这不是推广这些问题的最好方法,你会发表什么?

2 个答案:

答案 0 :(得分:2)

我认为这是一个问题,你可能想要一个抽象工厂用于你的生成器,而不是静态方法。您可以使用各个工厂的构造函数来传递具有不同参数的数据。每个人都有一个固定的Create方法。

interface IProblemFactory<T> where T : IProblem<T> 
{
    T Create();
}

class ArithmeticProblemFactory : IProblemFactory<Arithmetic> 
{
    private Tuple<int, decimal, decimal> condition;

    public ArithmeticProblemFactory(Tuple<int, decimal, decimal> condition) {
        this.condition = conditionl
    }

    Arithmetic IProblemFactory<Arithmetic>.Create() {
        ...
    }
}

答案 1 :(得分:1)

为了获得多态创建的行为,抽象因子模式最适合这种情况。有关如何进行设置的示例,请参阅Mark的答案。

但是你还需要能够用不同数量的参数检查答案。从您的示例中,您似乎始终期望每个参数都有decimal类型。假设这是正确的,您可以使CheckTheAnswer成为可变方法。我可能还建议添加一个多态属性来访问所需数量的参数。所以我们现在有:

public abstract class Problem<T>
{
    public abstract int ResultCount { get; }
    public abstract bool CheckTheAnswer(params decimal[] results);
}

基类可以是:

public class Arithmetic : Problem<Arithmetic>
{
    public override int ResultCount
    {
        get
        {
            return 2;
        }
    }

    public override bool CheckTheAnswer(params decimal[] results)
    {
        if(results.Length != ResultCount)
            throw new ArgumentException("Only expected " + ResultCount + " arguments.");
        ...
    }
}

虽然这不会在参数数量上提供编译时类型安全性,但它允许您使用运行时保证解决问题。