三、输出参数
输出参数不要求实参在调用方法前必须赋值,但必须执行前在方法内赋值。
另,输出参数可以一次调用输出多个参数。其他特性与引用参数一致,不再赘述。
using System;
namespace ConsoleOnlyTest
{
internal class Program
{
static void Main(string[] args)
{
Actor act = null;
bool b = Deyunshe.Create("郭德纲", 49,out act);
if (b == true)
{
Console.WriteLine("姓名:{0},年龄:{1}",act._name, act._age);
}
else
{
Console.WriteLine("查无此人");
}
}
}
class Actor
{
public string _name { get; set; }
public int _age { get; set; }
}
class Deyunshe
{
public static bool Create(string actor_name,int actor_age,out Actor result)
{
result = null;
if(string.IsNullOrEmpty(actor_name))
{
return false;
}
if (actor_age < 18 || actor_age > 90)
{
return false;
}
result =new Actor() { _name=actor_name, _age=actor_age};
return true;
}
}
}
四、数组参数
声明方法时写明是params数组参数,则在主函数中调用数组时,可以不单独声明数组,直接在调用方法的语句中写数组元素即可。
在每一个声明的方法中,只能有一个params数组参数,且数组参数必须在形参中的最后一个。否则代码无法理解该按什么数序处理主函数中简写的数组元素。
实际上,在平时用Console.WriteLine("{0}+{1}={2}",x,y,z)这类语句的写法时,本质上就是Console.WriteLine重载,声明了一个object类型的数组然后把x、y、z放进去,然后传进WriteLine方法中。
using System;
namespace ConsoleOnlyTest
{
internal class Program
{
static void Main(string[] args)
{
int result = CalculateScore(1, 2, 3, 4); //方法内写数组函数,则主函数里调用方法时直接写数组成员即可
Console.WriteLine(result);
}
public static int CalculateScore(params int[] intArray) //用params数组参数,可以让主函数中不用再单独声明数组
{
int sum = 0;
foreach (var i in intArray)
{
sum += i;
}
return sum;
}
}
另外,字符串string类型中有一个方法split,可以认为是Excel中的“分列”。指定符号进行分割,在调用时用 ' ' 隔开分隔符即可。
using System;
namespace ConsoleOnlyTest
{
internal class Program
{
static void Main(string[] args)
{
string str = "a,b;c.d/e。f、g";
string[] result = str.Split(',', '.', ';', '/', '。', '、'); //用单引号隔开分列关键字
foreach (var i in result)
{
Console.WriteLine(i);
}
}
public static int CalculateScore(params int[] intArray) //用params数组参数,可以让主函数中不用再单独声明数组
{
}
}
}
五、具名参数
具有名字的参数。优点有:
1:提高代码可读性,直接就能知道调用方法时各个变量的意义;
2:可以不用按照声明方法时规定的参数顺序去写了。
参考以下例子(与可选变量用同一个例子),此处“age:”和“name:”就是具名参数:
六、可选参数
在声明方法时用=给形参赋予默认值,就会让参数变成可选参数。声明了可选参数的,调用方法时可以不对变量进行赋值,变量就会使用默认值。参考以下例子:
using System;
namespace ConsoleOnlyTest
{
internal class Program
{
static void Main(string[] args)
{
Saysth();
Saysth(age: 800, name: "张君宝");
}
public static void Saysth(string name = "郭襄", int age = 20)
{
Console.WriteLine("My name is {0},I'm {1} years old.", name, age);
}
}
}
七、this参数(扩展方法)
对类中原本没有的方法进行扩展。
想使用this参数的方法,必须是公有、静态的,即被public、static修饰的方法,且该方法所属的类也必须是一个静态类static class;
参考以下例子,通过使用this参数给double类的所有变量都增加了一个求圆面积的方法。下面的例子中,即double类型的x可以直接调用GetCycleArea方法。
this参数,也即扩展方法,非常重要,后续很多高级内容都是通过该知识点来实现的,如LINQ方法(读作 link、lin Query均可)。
using System;
namespace ConsoleOnlyTest
{
internal class Program
{
static void Main(string[] args)
{
double x = 3.1415926;
double y = x.GetCycleArea(10); //通过this参数,给double类新增了方法 求圆面积
Console.WriteLine(y);
}
}
static class DoubleExtension
{
public static double GetCycleArea(this double pi, int r) //this参数必须在方法体内第一个,修饰的是第一个变量的类型
{
double S = r * r * pi;
return S;
}
}
}