c# - C#中如何在非静态方法中调用静态方法

标签 c# .net static-methods

如何在 c# 中的 non static 方法中调用 static 方法?

面试官给我的情景:

class class1
{

    public static void method1(){}

    public void method2()
    {
        //call method1()
    }

我们该怎么做

最佳答案

通常的做法是用类名调用静态方法。

参见:Static Classes and Static Class Members (C# Programming Guide)

The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.

所以你的电话会是这样的:

class1.method1();

但是没有必要

您可以调用没有类名的静态方法,例如:

method1();

但是你只能在拥有那个静态方法的类中这样做,你不能在那个类之外调用没有类名的静态方法。

关于c# - C#中如何在非静态方法中调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21532756/

相关文章:

c# - 如何解决 Ninject 模块内的依赖关系?

c# - 如何在 html 文档中包含 html 代码?

c# - 属性 "VisualTree"只能设置一次

c# - 我应该使用静态方法 (C#)

python - 指向 Python 中静态方法的指针

c# - 正则表达式 - 增量替换

.net - 如果队列为空,则停止 Rabbit MQ 消费者事件

c# - C# 的最佳实践。用await传递参数可以吗?

.net - VB.NET:TAB 的标识符?

java - 静态工厂方法中的泛型? ( java )