解析C#面向对象编程中方法(method)的使用

2019-12-26 17:33:36刘景俊
易采站长站为您分析解析C#面向对象编程中方法(method)的使用,方法是面向对象编程语言中的基本特性,需要的朋友可以参考下  

方法是包含一系列语句的代码块。程序通过调用该方法并指定任何所需的方法参数使语句得以执行。在 C# 中,每个执行的指令均在方法的上下文中执行。Main 方法是每个 C# 应用程序的入口点,并在启动程序时由公共语言运行时 (CLR) 调用。
方法签名
通过指定访问级别(如 public 或 private)、可选修饰符(如 abstract 或 sealed)、返回值、方法的名称以及任何方法参数,在类或结构中声明方法。这些部件一起构成方法的签名。
注意
出于方法重载的目的,方法的返回类型不是方法签名的一部分。但是在确定委托和它所指向的方法之间的兼容性时,它是方法签名的一部分。
方法参数在括号内,并且用逗号分隔。空括号指示方法不需要任何参数。此类包含三种方法:


abstract class Motorcycle
{
 // Anyone can call this.
 public void StartEngine() {/* Method statements here */ }

 // Only derived classes can call this.
 protected void AddGas(int gallons) { /* Method statements here */ }

 // Derived classes can override the base class implementation.
 public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; }

 // Derived classes must implement this.
 public abstract double GetTopSpeed(); 
}

方法访问
调用对象上的方法就像访问字段。在对象名之后添加一个句点、方法名和括号。参数列在括号里,并且用逗号分隔。因此,可在以下示例中调用 Motorcycle 类的方法:


class TestMotorcycle : Motorcycle
{

 public override double GetTopSpeed()
 {
  return 108.4;
 }

 static void Main()
 {

  TestMotorcycle moto = new TestMotorcycle();

  moto.StartEngine();
  moto.AddGas(15);
  moto.Drive(5, 20);
  double speed = moto.GetTopSpeed();
  Console.WriteLine("My top speed is {0}", speed);   
 }
}

方法参数与参数
该方法定义指定任何所需参数的名称和类型。调用代码调用该方法时,它为每个参数提供了称为参数的具体值。参数必须与参数类型兼容,但调用代码中使用的参数名(如果有)不需要与方法中定义的参数名相同。例如:


public void Caller()
{
 int numA = 4;
 // Call with an int variable.
 int productA = Square(numA);

 int numB = 32;
 // Call with another int variable.
 int productB = Square(numB);

 // Call with an integer literal.
 int productC = Square(12);

 // Call with an expression that evaulates to int.
 productC = Square(productA * 3);
}

int Square(int i)
{
 // Store input argument in a local variable.
 int input = i;
 return input * input;
}