什么是“静态方法"?在 C# 中? [英] What's a "static method" in C#?

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

问题描述

在方法中添加 static 关键字是什么意思?

What does it mean when you add the static keyword to a method?

public static void doSomething(){
   //Well, do something!
}

你能在类中添加 static 关键字吗?那么这意味着什么?

Can you add the static keyword to class? What would it mean then?

推荐答案

static 函数与常规 (instance) 函数不同,它不与班级.

A static function, unlike a regular (instance) function, is not associated with an instance of the class.

static 类是一个只能包含 static 成员的类,因此不能被实例化.

A static class is a class which can only contain static members, and therefore cannot be instantiated.

例如:

class SomeClass {
    public int InstanceMethod() { return 1; }
    public static int StaticMethod() { return 42; }
}

为了调用InstanceMethod,你需要一个类的实例:

In order to call InstanceMethod, you need an instance of the class:

SomeClass instance = new SomeClass();
instance.InstanceMethod();   //Fine
instance.StaticMethod();     //Won't compile

SomeClass.InstanceMethod();  //Won't compile
SomeClass.StaticMethod();    //Fine

这篇关于什么是“静态方法"?在 C# 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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