out在使用之前必须在方法里面为out参数赋值,out参数无法获取传递进来的变量的值,只能给传递进来的变量赋值,out参数在方法执行完毕之前必须赋值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
//一个方法只有一个返回值,只能return一个值,当需要返回多个值的时候,可以用out
int m, n;
Test(out m, out n);
Console.WriteLine(m + "-----------" + n);
//int.TryParse方法的返回值为布尔类型,转换成功返回真,失败返回假
//但是还得取到转换成功后的值,就用了out参数,来把转换成功后的值传出来
string s = "333";
int r;
bool b = int.TryParse(s, out r);
if (b)
{
Console.WriteLine("转换成功,值为{0}", r);
}
else
{
Console.WriteLine("转换失败,值为{0}", r);
}
//ref,
int p = 1000;
Test1(ref p);
Console.WriteLine(p);
Test2(ref p);
Console.WriteLine(p);
Console.ReadKey();
}
public static void Test(out int m, out int n)
{
m = 100;
n = 10;
}
public static void Test1(ref int a)
{
a = a + 100;
}
public static void Test2(ref int b)
{
b = b + 10;
}
}
}
可变参数
如果方法有多个参数,可变参数必须在最后一个,
可变参数可以传递参数,也可以不传递参数,不传递参数,则args数组为一个长度为0的数组。
可变参数可以直接传递一个数组进来。
public static void Abc(string msg,params int[] args) { }
使用的时候
int[] ss = new int []{ 1, 2, 1, 2, 1 };
Abc("123", ss);