【问题标题】:What is the purpose of 'arguments' in square brackets? C# [duplicate]方括号中“参数”的目的是什么? C# [重复]
【发布时间】:2018-10-15 09:25:15
【问题描述】:

我在看教程时遇到了这个问题。以前没见过,我想知道这里发生了什么。

    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 行,几乎没有解释原因。 具体来说,我想知道方括号。我知道数组,我知道注释,但这看起来不同。

【问题讨论】:

标签: c# asp.net-mvc brackets square


【解决方案1】:

那是indexer。基本上它看起来像使用数组,但它可以有多个参数,而且它们不必是整数。就像属性一样,索引器可以有一个 get 访问器和/或一个 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> 声明了一个 T 类型的读/写索引器,带有一个 int 参数
  • IDictionary<TKey, TValue> 声明了一个 TValue 类型的读/写索引器,带有一个 TKey 参数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多