当静态成员在类中时如何调用它(这是普通类)

  • 本文关键字:静态成员 调用 何调用 c#
  • 更新时间 :
  • 英文 :


在一次面试中,我遇到了这个问题,我怎么能在这里称呼静态成员:

 public  class PermenatEmployee
 {
      public static string/void sayGoodBye()
      {
          return "GoodBye";
      }
 }
 static void Main(string[] args)
 {
     var gsgsg = PermenatEmployee.sayGoodBye;
 }

在这里,我可以选择在方法中使用stringvoid

删除字符串/空。

代码将如下所示:

public class PermenatEmployee
{
    public static string sayGoodBye()
    {
        return "GoodBye";
    }
    private static void Main(string[] args)
    {
        var gsgsg = PermenatEmployee.sayGoodBye();
    }
}

如果你真的想返回一个字符串和一个 void,你可以在方法上使用 void 的返回类型,然后使用字符串的 out 参数,如下所示:

 public class PermenatEmployee
{
    public static void SayGoodBye(out string action)
    {
        action = "GoodBye";
    }
    private static void Main(string[] args)
    {
        PermenatEmployee.SayGoodBye(out var action);
        Console.WriteLine(action);
    }
}

我对这里的语法感到非常困惑: string/void ,如果要指示它可能是其中之一,那么要进行静态函数调用,您需要使用 () 调用该函数,即:

var gsgsg = PermenatEmployee.sayGoodBye()

话虽如此,您不能将void的返回值分配给var

您也不能拥有类范围之外的方法,因此您的示例将无法编译。

在你的类中 PermenatEmployee:

public class PermenatEmployee
{
    public static string sayGoodBye()
    {
        return "GoodBye";
    }
} 

在您的程序类中:

static void Main(string[] args)
{
    Console.WriteLine(PermenatEmployee.sayGoodBye());
}

你可以用它的名字来称呼它,

 public  class PermenatEmployee
 {
  public static string/void sayGoodBye()
  {
      return "GoodBye";
  }
 }
 static void Main(string[] args)
 {
 var gsgsg = sayGoodBye(); // your answer
}

最新更新