如何在 C# 中定义自定义方法?
要在 C# 中定义自定义方法,请使用以下语法 -
<Access Specifier> <Return Type> <Method Name>(Parameter List) {
Method Body
}以下是方法的各个组成部分 -
访问说明符 - 这决定了从另一个类中访问变量或方法的可见性。
返回类型 - 方法可以返回一个值。返回类型是方法返回的值的数据类型。如果该方法不返回任何值,则返回类型为 void。
方法名称 - 方法名称是唯一标识符,并区分大小写。它不能与类中声明的任何其他标识符相同。
参数列表 - 括在圆括号中,参数用于从方法传递和接收数据。参数列表是指类型、顺序和方法参数的数量。参数是可选的;也就是说,方法可以不包含任何参数。
方法正文 - 包含完成所需活动所需的一组指令。
让我们看一个示例 -
示例
using System;
namespace Demo {
class NumberManipulator {
public int FindMax(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
static void Main(string[] args) {
/* local variable definition */
int a = 90;
int b = 15;
int ret;
NumberManipulator n = new NumberManipulator();
//calling the FindMax method
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}输出
Max value is : 90
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
JavaScript
PHP