杭州网站建设V芯ee8888e,小说网站怎么做,做展板好的网站,html在哪里写代码目录 C#方法方法参数默认参数值多个参数返回值命名参数 方法重载 C#方法
实例 在程序类内创建一个方法#xff1a;
class Program
{static void MyMethod() //static 静态意味着方法属于程序类#xff0c;而不是程序类的对象。void 表示此方法没有返回值。MyMethod() 是方法… 目录 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);
}