2.C#引用参数ref与输出参数out

ref与out在以下代码中都可编译成功 但是有本质上的区别

static void Test(ref int i)
{
     i = 2;
}
static void Main(string[] args)
{
    int a = 1;
    Test(ref a);
}

ref可将在Main方法中定义的参数a读取到

static void Test(ref int i)
{
    Console.WriteLine(i);
    i = 2;
    i++;
    Console.WriteLine(i);
}
static void Main(string[] args)
{
    int a = 1;
    Test(ref a);
    Console.WriteLine(a);
}

out读取不到Main方法中的参数a 因此在Test方法中必须对其进行初始化

static void Test(out int i)
{
    i = 2;
    i++;
    Console.WriteLine(i);
}
static void Main(string[] args)
{
    int a = 1;
    Test(out a);
    Console.WriteLine(a);
}

结论:
ref用于读取参数并对其进行操作
out强制该参数必须重新初始化

猜你喜欢

转载自blog.csdn.net/Chen104617590/article/details/81435000