如何在类中使方法调用另一个?

现在我有两个班allmethods.cscaller.cs

我上课有一些方法allmethods.cs。我想编写代码caller.cs以便在allmethods类中调用某个方法。

代码示例:

public class allmethods

public static void Method1()

{

// Method1

}

public static void Method2()

{

// Method2

}

class caller

{

public static void Main(string[] args)

{

// I want to write a code here to call Method2 for example from allmethods Class

}

}

我该如何实现?

回答:

因为Method2是静态的,所以您要做的就是这样调用:

public class AllMethods

{

public static void Method2()

{

// code here

}

}

class Caller

{

public static void Main(string[] args)

{

AllMethods.Method2();

}

}

如果它们在不同的命名空间中,则还需要AllMethodsusing语句中将的命名空间添加到caller.cs中。

如果要调用实例方法(非静态),则需要一个类的实例来调用该方法。例如:

public class MyClass

{

public void InstanceMethod()

{

// ...

}

}

public static void Main(string[] args)

{

var instance = new MyClass();

instance.InstanceMethod();

}

从C#6开始,您现在还可以使用using static指令实现这一点,以更优雅地调用静态方法,例如:

// AllMethods.cs

namespace Some.Namespace

{

public class AllMethods

{

public static void Method2()

{

// code here

}

}

}

// Caller.cs

using static Some.Namespace.AllMethods;

namespace Other.Namespace

{

class Caller

{

public static void Main(string[] args)

{

Method2(); // No need to mention AllMethods here

}

}

}

  • 静态类和静态类成员(C#编程指南)
  • 方法(C#编程指南)
  • using static 指令(C#参考)

以上是 如何在类中使方法调用另一个? 的全部内容, 来源链接: utcz.com/qa/416285.html

回到顶部