如何在C#中的非静态方法中调用静态方法 [英] how to call static method inside non static method in 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.
始终通过类名访问静态成员,而不是通过实例名称.静态成员只有一个副本,无论创建了多少个该类的实例.
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屋!