如何在C#中的非静态方法中调用静态方法 [英] how to call static method inside non static method in c#

查看:138
本文介绍了如何在C#中的非静态方法中调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

how to call static method inside non static method in c# ?

面试官给了我方案:

class class1
{

    public static void method1(){}

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

我们怎么做到

推荐答案

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

A normal practice is to call static method with class name.

请参阅:静态类和静态类成员(C#编程)指南)

始终通过类名访问静态成员,而不是通过实例名称.静态成员只有一个副本,无论创建了多少个该类的实例.

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();

但这不必要

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

You can call the static method without class name like:

method1();

但是您只能在包含该静态方法的类内部执行此操作,如果没有该类外部的类名称,则无法调用静态方法.

But you can only do that inside the class which holds that static method, you can't call static method without class name outside of that class.

这篇关于如何在C#中的非静态方法中调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆