c# 静态方法是怎么用? 我这段代码为什么不能定义非静态的方法呢

来源:百度知道 编辑:UC知道 时间:2024/05/18 08:10:49
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
public static int aa(int x, int y)
{
int z;
z = x + y;
return z;
}
static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine ());
int b = int.Parse(Console.ReadLine ());
int s;
s = aa(a, b);
Console.WriteLine("{0}", s);
Console.ReadKey();
}
}
}

静态方法好像就是可以直接用,不需要前边加对象的名字。你现在用的就是aa就是个静态方法。如果要用非静态的,就把关键字去掉。然后这个aa就是program类的方法了,如果你要用,就得先实例化一个program的对象z,就是program z=new program();然后s=z.aa(a,b);就可以了。关于实例化你不知道具体的话就当做固定格式。其实是有很多种方式的。

把static关键字去掉就可以。但是aa没有使用任何Program类成员,如果运行代码分析会对这一点产生警告

静态方法是属于一个类的,这个类的所有对象都共同拥有此方法,因此在调用时直接用(类名.方法名)调用.静态方法只能『直接调用同一个类』中的『静态』方法,因为Main方法为静态,它想调用同一个类中的aa方法,则aa必须为静态方法。希望对你有帮助…