方括号中 'arguments' 的目的是什么? C#

What is the purpose of 'arguments' in square brackets? C#

我在观看教程时 运行 对此感兴趣。以前没看过,想知道这里是怎么回事

    Application["ApplicationStartDateTime"] = DateTime.Now;

这是在上下文中:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        Application["ApplicationStartDateTime"] = DateTime.Now;
    }
    protected void Application_End()
    {
        Application.Clear();
    }
}

application_Start 方法是样板,除了添加的 StartDateTime 行,几乎没有解释原因。 具体来说,我想了解方括号。我知道数组,也知道注释,但这看起来不一样。

那是 indexer。基本上它看起来像使用数组,但它可以有多个参数,而且它们不必是整数。就像 属性 一样,索引器可以有一个 get 访问器 and/or 一个 set 访问器。

它们是这样声明的:

public class Container
{
    public string this[int x, int y]
    {
        get { /* code here */ }
        set { /* code here using value */ }
    }
}

这是一个 string 类型的索引器,它有两个 int 参数。所以我们可以写:

Container container = new Container();
string fetched = container[10, 20];
container[1, 2] = "set this value";

索引器最常用于集合:

  • IList<T> 使用单个 int 参数
  • 声明类型 T 的 read/write 索引器
  • IDictionary<TKey, TValue> 使用单个 TKey 参数
  • 声明类型 TValue 的 reader/write 索引器