gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:48:56 26 4
gpt4 key购买 nike

现在我有两个类 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();
}
}

如果它们位于不同的命名空间中,您还需要在 using 语句中将 AllMethods 的命名空间添加到 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# - 如何使方法在类中调用另一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16226444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com