Dot-Net

Environment.GetCommandLineArgs - 為什麼它是一種方法?為什麼不是財產?

  • March 8, 2012

我試圖了解創建該方法的團隊的設計注意事項Environment.GetCommandLineArgs

它可能是一個靜態屬性,非常像System.Web.HttpContext.Current. 畢竟,返回的值一旦可用就不應改變。所以它更像是目前執行程序的一個屬性。

我知道 .NET 中的任何屬性都是 getter/setter 方法的語法糖。但這正是使用屬性而不是顯式 getter 方法的確切原因。

或者也許我在這裡缺少一些東西?

你怎麼看?

我懷疑這是因為每次呼叫它時它都會複製數組。例如,考慮這個程序:

using System;

public class Test
{
   static void Main(string[] args)
   {
       string[] argsCopy = Environment.GetCommandLineArgs();
       args[0] = "x";

       // 0 is the command in this case
       argsCopy[1] = "y";

       string[] argsCopy2 = Environment.GetCommandLineArgs();
       Console.WriteLine(argsCopy2[1]);
   }
}

如果你用“test original”執行它,它仍然會列印出“original”。

所以當你說:

畢竟,返回的值一旦可用就不應改變。

實際上,它會在每次呼叫時返回一個不同的值(一個新的數組引用),正是因為數組總是可變的。

引用自:https://stackoverflow.com/questions/9614640