0

我想有一个接口来解决一个叫做IProblem. 有两种方法:Solve() 和 CheckArguments()。该类Problem将实现 CheckArguments() 函数,因为它对于所有问题都是相同的。但是后来我遇到了不同类型的问题,例如EasyProblemSolve HardProblem() 方法的不同实现,但 CheckArguments() 方法总是相同的,我总是想使用基类 Problem() 的实现。

我想有正确的修饰符,我对在哪个类/接口中定义哪个方法有点困惑。更不用说我也有这两个功能的测试项目。

4

3 回答 3

3

我不确定您的问题是否是“使用什么”,但我建议使用接口和抽象类:

public interface IProblem {
    void Solve();
    void CheckArguments();
}

public abstract class Problem : IProblem {
    public abstract void Solve();
    public void CheckArguments() {
        ...
    }
}

public class EasyProblem : Problem
{
    public override void Solve()
    {
        ....
    }
}

这样,检查参数在基类中实现,所有派生类都实现 IProblem,每个派生类都必须实现 Solve。

如果你省略了接口并且只支持派生自 的类Problem,你将确保给定的类不能给它自己的CheckArguments().

public abstract class Problem {
    public abstract void Solve();
    public void CheckArguments() {
        ...
    }
}

public class EasyProblem : Problem
{
    public override void Solve()
    {
        ....
    }
}

...
static Main(string[] args)
{
    List<Problem> problemsToSolve = ...
    foreach(var problem in problemsToSolve)
    {
        problem.CheckArguments();
        problem.Solve();
    }
}    
于 2013-11-06T09:11:37.737 回答
3

您可以尝试以下方法:

public interface ISupportArguments
{
   bool CheckArguments();
}

public abstract class AbstractProblem : ISupportArguments
{
   public bool CheckArguments() {
        return true;
   }

   public abstract void SolveProblem();
}

所以你的每个类都派生自 AbstractProblem 并覆盖它自己的版本

SolveProblem(..)
于 2013-11-06T09:13:50.737 回答
0

The class structure has been shown by Matten very well.
As regards access modifiers: I'd propose a defensive approach, so that you use the most restrictive access modifier that solves the problem. It is easier to be less restrictive afterwards than to be more restrictive as you might have to explain to some users of your code why they cannot use it anymore.

So for the types (interface and classes): if you don't need them in other assemblies, rather define them as internal. If you want to access the types from your test project, you can use the InternalsVisibleTo attribute to be able to access them from specific assemblies. You add the attribute to the assembly containing the types and provide the name (and for strong named assemblies some additional data) of the test assembly as a parameter.

The same applies to the members. You can also think about implementing the interface explicitly, so you can access the methods only if you access the class via the interface.

于 2013-11-06T09:21:41.750 回答