C#静态方法与非静态方法
C#的类中可以包含两种方法:静态方法和非静态方法。
使用了static 修饰符的方法为静态方法,反之则是非静态方法。
静态方法是一种特殊的成员方法,它不属于类的某一个具体的实例,而是属于类本身。所以对静态方法不需要首先创建一个类的实例,而是采用类名.静态方法的格式 。
下面是一个使用静态方法的简单例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int i = MyClass.Add(7, 11); //调用静态方法 Console.WriteLine(i); Console.ReadKey(); } } class MyClass { public static int Add(int x, int y) { return x + y; } } }
输出结果:18
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/221721.html原文链接:https://javaforall.net
