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

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

问题描述

当您添加static关键字的方法是什么意思?

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

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

你能添加静态关键字来上课?会是什么话呢?

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

推荐答案

A 静态功能,不同于一般的(实例的)功能,是不与类的实例相关联。

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

A 静态类是只能包含静态成员,因此不能被实例化的类。

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天全站免登陆