在方法中将引用类型设置为null

时间:2017-08-25 17:10:17

标签: c#

调用my方法后,为什么vowels不为空? string []是引用类型,我不明白?

using System;

class Program
{
  public static string[] vowels = {"A", "E", "I", "O", "U"};

  public static void SetArrayToNull(string[] array)
  {
    array = null;
  }

  public static void Main(string[] args)
  {
    SetArrayToNull(vowels);
    Console.WriteLine(vowels == null); //writes "false"
  }
}

1 个答案:

答案 0 :(得分:-2)

您应该使用ref关键字。

正如您在此处所见:https://docs.microsoft.com/en-en/dotnet/csharp/language-reference/keywords/ref

因为,您的主要问题是您作为参数传递的变量仅在SetArrayToNull方法的局部范围内修改。

但是,通过使用ref关键字,您将避免这种情况。因为您在此方法的本地范围内所做的更改将在您调用之外更新。

这很简单:

using System;

class Program
{
  public static string[] vowels = {"A", "E", "I", "O", "U"};

  public static void SetArrayToNull(string[] array)
  {
    array = null;
  }

  public static void Main(string[] args)
  {
    SetArrayToNull(ref vowels);
    Console.WriteLine(vowels == null); //now, it will writes "true" :)
  }
}