c#编程基础学习之方法

目录

C#方法

实例

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

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

1、在C#中,命名方法时最好以大写字母开头,因为这样可以使代码更易于阅读;

2、定义方法名称后跟括号();

3、定义一次代码,多次使用,用于执行某些操作时也称为函数;

4、调用(执行)一个方法,写下方法名,后跟括号()分号.

方法参数

参数分形参实参,参数在方法中充当变量

参数在方法名称后面的括号内指定,可以同时添加多个参数,用逗号分隔开即可。

实例

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

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

// Liam Refsnes

默认参数值

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

例:

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

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

// Sweden
// Norway

多个参数

实例

csharp 复制代码
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关键字:

实例

csharp 复制代码
static int MyMethod(int x) 
{
  return 5 + x;
}

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

// 输出 8 (5 + 3)

命名参数

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

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

实例

csharp 复制代码
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)

实例

csharp 复制代码
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);
}
相关推荐
hez20101 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉7 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫8 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫9 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6259 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902119 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠10 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫12 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech12 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf14 天前
C#摸鱼实录——IoC与DI案例详解
c#