简体   繁体   English

C# 我该如何使用这个方法?

[英]C# How can I use this as a method?

Original: I am using if statements in many methods.原文:我在许多方法中使用 if 语句。 My original code works.我的原始代码有效。 But, it would be nice to create a method for them so I can call it every time I want to use it.但是,为它们创建一个方法会很好,这样我每次想使用它时都可以调用它。

private void method()
{
  if (page_name == "SpecificPageName")
  {
      if (!TableHasElements)
      {
         // A: do something
         return;
      }
      else if (role != instructor)
      {
         // B: message("Access Denied")
         return;
      }
  }
  **// C: Open Page**
}

I would like to create a method for the if statements: However, when I make a method and call the method it should be able to run "C" when A and B conditions are not met.我想为 if 语句创建一个方法:但是,当我创建一个方法并调用该方法时,它应该能够在不满足 A 和 B 条件时运行“C”。

private void methodIWouldLikeToCall()
{
    if (!TableHasElements)
    {
        // A: do something
        return;
    }
    else if (role != instructor)
    {
        // B: message("Access Denied")
        return;
    }
}
private void method()
{
    if (page_name == "SpecificPageName")
    {
        methodIWouldLikeToCall();
    }
    // C: Open Page**
}

Your new method needs to return a result that will enable you to decide whether or not to continue with the original method, eg您的新方法需要返回一个结果,使您能够决定是否继续使用原始方法,例如

private bool methodIWouldLikeToCall()
{
    if (!TableHasElements)
    {
        // A: do something
        return true;
    }
    else if (role != instructor)
    {
        // B: message("Access Denied")
        return true;
    }

     return false;
}

private void method()
{
    if (page_name == "SpecificPageName")
    {
        if (methodIWouldLikeToCall())
        {
            return;
        }
    }
    **// C: Open Page**
}

You may want to reverse the use of true and false if that is more natural in the circumstances.如果在这种情况下更自然,您可能希望false true You might also remove the nesting in the original method and use a single if statement with && , if that's appropriate.如果合适的话,您还可以删除原始方法中的嵌套并使用带有&&的单个if语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM