【问题标题】:Call method1 before calling other methods in class在调用类中的其他方法之前调用 method1
【发布时间】:2014-10-20 14:30:42
【问题描述】:

我已经用以下类构建了一个类库

public class Class1
{
    public Class1()
    {
    }

    public void Method1()
    {
        //user should call this method before Method2
    }

    public void Method2()
    {
        //user should call Method1 before calling this method
    }
}

如何防止用户在调用Method1之前调用Method2? 谢谢

【问题讨论】:

  • 不要在公共界面中放置任何用户不应该使用的东西。
  • 用户需要同时调用它们
  • 那你需要重新设计。

标签: c# .net class oop


【解决方案1】:

在调用第一个方法时设置一个标志:

public class Class1
{
    private bool hasCalledMethod1;

    public Class1()
    {
    }

    public void Method1()
    {
        //user should call this method before Methode2

        hasCalledMethod1 = true;
    }

    public void Method2()
    {
        if (!hasCalledMethod1)
        {
            throw new InvalidOperationException("Must call Method1 before calling Method2");
        }

        //user should call Methode1 before calling this method
    }
}

【讨论】:

  • 我不需要标志或异常,这将在运行时抛出异常。我需要防止他在编码时调用它。也许使用属性或类似的东西
  • @asem 您不能在编译时强制执行此操作。使用文档和例外。
【解决方案2】:

为什么不通过在Method2() 中调用Method1() 来强制执行此操作,如下所示

public void Method2()
{
       Method1();
      //Do rest of the work here     
}

因此,每当用户直接调用Method2() 而不调用Method1() 时,它将确保在处理Method2() 正文开始之前已经处理了Method1()

【讨论】:

    猜你喜欢
    • 2022-12-14
    • 1970-01-01
    • 2013-07-24
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多