c#编程基础学习之方法

C#方法

实例
在程序类内创建一个方法:

class Program
{
  static void MyMethod() //static 静态意味着方法属于程序类,而不是程序类的对象。void 表示此方法没有返回值。MyMethod() 是方法的名称
  {
    // 要执行的代码
  }
}

1、在C#中,命名方法时最好以大写字母开头,因为这样可以使代码更易于阅读;
2、定义方法名称后跟括号();
3、定义一次代码,多次使用,用于执行某些操作时也称为函数;
4、调用(执行)一个方法,写下方法名,后跟括号()分号.

方法参数

参数分形参实参,参数在方法中充当变量
参数在方法名称后面的括号内指定,可以同时添加多个参数,用逗号分隔开即可。
实例

static void MyMethod(string fname) //该方法将名为fname的string字符串作为参数。
{
  Console.WriteLine(fname + " Refsnes");
}

static void Main(string[] args)
{
  MyMethod("Liam");	//Liam是实参
  
}

// Liam Refsnes

默认参数值

定义方法的时候在括号里使用等号,调用方法时不带实参则会默认使用此值,
例:

static void MyMethod(string country = "Norway") //默认值的参数通常称为可选参数。country是一个可选参数,"Norway"是默认值。
{
  Console.WriteLine(country);
}

static void Main(string[] args)
{
  MyMethod("Sweden");
  MyMethod();	//不带参数调用方法,使用默认值Norway
}

// Sweden
// Norway

多个参数

实例

static void MyMethod(string fname, int age) 
{
  Console.WriteLine(fname + " is " + age);
}

static void Main(string[] args)
{
  MyMethod("Liam", 5);
  MyMethod("Jenny", 8);	//使用多个参数时,方法调用的参数数必须与参数数相同,并且参数的传递顺序必须相同。
}

// Liam is 5
// Jenny is 8

返回值

使用的void关键字表示该方法不应返回值。如果希望方法返回值,可以使用基本数据类型(如int 或double)而不是void,并在方法内使用return关键字:

实例

static int MyMethod(int x) 
{
  return 5 + x;
}

static void Main(string[] args)
{
  Console.WriteLine(MyMethod(3));
}

// 输出 8 (5 + 3)

命名参数

也可以使用 key: value语法发送参数。

这样,参数的顺序就无关紧要了;

实例

static void MyMethod(string child1, string child2, string child3) 
{
  Console.WriteLine("The youngest child is: " + child3);
}

static void Main(string[] args)
{
  MyMethod(child3: "John", child1: "Liam", child2: "Liam");
}

// 最小的孩子是: John

方法重载

使用方法重载,只要参数的数量类型不同,多个方法可以具有相同的名称不同的参数;

实例

int MyMethod(int x)
float MyMethod(float x)
double MyMethod(double x, double y)

实例

static int PlusMethod(int x, int y)	//方法名相同
{
  return x + y;
}

static double PlusMethod(double x, double y)	//参数类型不同
{
  return x + y;
}

static void Main(string[] args)
{
  int myNum1 = PlusMethod(8, 5);
  double myNum2 = PlusMethod(4.3, 6.26);
  Console.WriteLine("Int: " + myNum1);
  Console.WriteLine("Double: " + myNum2);
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>