一、方法重载
<span style="font-size:18px;">//方法重载。与参数有关,返回值无关
//因为有重载,所以可以放不同类型的值
//为什么要重载?方便。</span>
二、返回数组
<span style="font-size:18px;">static void Main(string[] args)
{
int[] nums = { 1, 2, 3, 4, 5, 6, 7 };
int[] arrayNumbers = ArraySumMaxorMIn(nums);
Console.WriteLine("最大值{0}", arrayNumbers[0]);
Console.WriteLine("最小值{0}", arrayNumbers[1]);
Console.WriteLine("和{0}", arrayNumbers[2]);
Console.ReadKey();
}
//返回一个数组
//方法求 和 最大值 最小值
public static int[] ArraySumMaxorMIn(int[] numbers)
{
int[] array = new int[3];
array[0] = int.MinValue;
array[1] = int.MaxValue;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] > array[0])
{
array[0] = numbers[i];
}
if (numbers[i] < array[1])
{
array[1] = numbers[i];
}
array[2] += numbers[i];
}
return array;
}</span>
二、out/ref
1.out
<span style="font-size:18px;"> static void Main(string[] args)
{
//out 传值:方法的参数使用了out,只能方法内部对参数赋值
//ref 传址
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int max;
int min;
int sum = Arraysum(nums, out max, out min);
Console.WriteLine("{0},{1},{2}",sum ,max ,min );
Console.ReadKey ();
}
public static int Arraysum(int[] numbers,out int max,out int min)
{
max = int.MinValue;
min = int.MaxValue;
int sum = 0;
for(int i=0;i<numbers .Length ;i++)
{
if (numbers [i]>max)
{
max = numbers[i];
}
if (numbers [i]<min)
{
min = numbers[i];
}
sum += numbers[i];
}
return sum;
}</span>
2.ref
static void Main(string[] args)
{
int number = 99;
int num = show(ref number);
Console.WriteLine("{0},{1}",num,number);//num是109,number是99
Console.ReadKey();
}
public static int show(ref int num)
{
return num + 10;//ref可以不给参数赋值。
}
四、自己写tryparse方法
<span style="font-size:18px;"> static void Main(string[] args)
{
Console.WriteLine("请输入一个数字");
string strNumber = Console.ReadLine();
int num;
bool result = Program.MytryParse(strNumber, out num);
if (result)
{
Console.WriteLine(num);
Console.ReadKey();
}
}
//自己写tryparse 方法
public static bool MytryParse(string s, out int result)
{
result = 0;
while (true)
{
try
{
result = Convert.ToInt32(s);
return true;
}
catch
{
Console.WriteLine("格式错误,请输入数字");
s = Console.ReadLine();//输入错误后,可以继续输入
}
}
}</span>