方法Add1、Add2和Multiply
Add1、Multiply都是静态的方法,所以可以不通过创建对象而只用“类名.方法”名调用即可;方法Add1和Main方法同在一个类Program中,因此省略“方法名.”。
非静态方法Add2只能通过实例化的方法来调用;否则会报13行的错误。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 方法_静态_非静态_
{
class Program
{
static void Main( string[] args )
{
int nRes1 = Add1( 1, 3 );
Program A = new Program(); // 报错::非静态的字段、方法或属性“方法_静态_非静态_.Program.Add2(int, int)”要求对象引用
int nRes2 = A.Add2( 7, 100 );
int nRes3 = Fangfa.Multiply( 3, 5 );
Console.WriteLine( nRes1 );
Console.WriteLine( nRes2 );
Console.WriteLine( nRes3 );
Console.ReadKey();
}
public static int Add1( int x, int y )
{
return x + y;
}
public int Add2( int x, int y )
{
return x + y;
}
}
static class Fangfa
{
public static int Multiply( int x, int y )
{
return x * y;
}
}
}