这句话的意思是什么[string key]?

19

我查看了来自Microsoft.AspNetCore.Http程序集的IRequestCookieCollection代码:

  //
  // Summary:
  //     Represents the HttpRequest cookie collection
  [DefaultMember("Item")]
  public interface IRequestCookieCollection : IEnumerable<KeyValuePair<string, string>>, IEnumerable
  {
    //
    // Summary:
    //     Gets the value with the specified key.
    //
    // Parameters:
    //   key:
    //     The key of the value to get.
    //
    // Returns:
    //     The element with the specified key, or string.Empty if the key is not present.
    //
    // Exceptions:
    //   T:System.ArgumentNullException:
    //     key is null.
    //
    // Remarks:
    //     Microsoft.AspNetCore.Http.IRequestCookieCollection has a different indexer contract
    //     than System.Collections.Generic.IDictionary`2, as it will return string.Empty
    //     for missing entries rather than throwing an Exception.
    string this[string key] { get; }

    //
    // Summary:
    //     Gets the number of elements contained in the Microsoft.AspNetCore.Http.IRequestCookieCollection.
    //
    // Returns:
    //     The number of elements contained in the Microsoft.AspNetCore.Http.IRequestCookieCollection.
    int Count { get; }
    //
    // Summary:
    //     Gets an System.Collections.Generic.ICollection`1 containing the keys of the Microsoft.AspNetCore.Http.IRequestCookieCollection.
    //
    // Returns:
    //     An System.Collections.Generic.ICollection`1 containing the keys of the object
    //     that implements Microsoft.AspNetCore.Http.IRequestCookieCollection.
    ICollection<string> Keys { get; }

    //
    // Summary:
    //     Determines whether the Microsoft.AspNetCore.Http.IRequestCookieCollection contains
    //     an element with the specified key.
    //
    // Parameters:
    //   key:
    //     The key to locate in the Microsoft.AspNetCore.Http.IRequestCookieCollection.
    //
    // Returns:
    //     true if the Microsoft.AspNetCore.Http.IRequestCookieCollection contains an element
    //     with the key; otherwise, false.
    //
    // Exceptions:
    //   T:System.ArgumentNullException:
    //     key is null.
    bool ContainsKey(string key);
    //
    // Summary:
    //     Gets the value associated with the specified key.
    //
    // Parameters:
    //   key:
    //     The key of the value to get.
    //
    //   value:
    //     The key of the value to get. When this method returns, the value associated with
    //     the specified key, if the key is found; otherwise, the default value for the
    //     type of the value parameter. This parameter is passed uninitialized.
    //
    // Returns:
    //     true if the object that implements Microsoft.AspNetCore.Http.IRequestCookieCollection
    //     contains an element with the specified key; otherwise, false.
    //
    // Exceptions:
    //   T:System.ArgumentNullException:
    //     key is null.
    bool TryGetValue(string key, out string value);
  }

并且无法理解该语句的含义

this[string key]

means. 有人能解释一下吗?

4个回答

22

这是一个索引器。它定义了一个索引属性,可以使用objectName["key"]来访问对象集合,例如Dictionary<string,T>

实现代码可能如下所示:

string this[string key]
{ 
    get{return _internalDictionary[key];}
}

或者这个:

string this[string key]
{ 
    get
    {
        switch(key)
        {
            case "Length":
                return this.Length;
            case "Timeout":
                return this.Timeout.ToString();
            case "Version":
                return "1.5.0";
        }
        return null;
    }
}

16

它就像一个方法但是不同

实际上,这只是一种特殊类型的函数。例如,想象一下你有这个类:

class MyClass {
    public string GetValue(string name) {
        switch(key)
        {
            case "Name":
                return "John";
            case "Age":
                return 30;
        }
    }
}
这段代码的调用方式当然是这样的:
// Calling a regular method
var instance = new MyClass();
var value = instance.GetValue("Name");
Console.WriteLine(value);
// Output: John

现在更改一些内容,以便您使用“索引器”语法。

  1. 不要再使用方法名“GetValue”,而是使用关键字“this”。
  2. 在参数周围不要使用圆括号,而要使用方括号

应用这些步骤:

  • string GetValue(string name) 变成
  • string this[string name]

为了更容易地想象,想象一下您的原始函数不叫 GetValue() 而叫 This(),那么:

  • string This(string name) 变成
  • string this[string name]

完整代码:

class MyClass {
    // public string GetValue(string name) {
    public string this[string name] {
        switch(key)
        {
            case "Name":
                return "John";
            case "Age":
                return 30;
        }
    }
}

在调用索引器时,您需要省略函数名称,并再次使用方括号而不是圆括号。因此,instance.GetValue("Name") 变为 instance["Name"]

完整代码:

// Calling a regular method
var instance = new MyClass();

// Remove the dot (.) and the function name
// Instead of parenthesis use square brackets

// var value = instance.GetValue("Name");
var value = instance["Name"];

Console.WriteLine(value);
// Output: John

何时应该使用索引器而不是方法?

任何时候都可以,只要你觉得有意义。通常情况下,当对象存储动态键入值(例如Dictionary<TKey,TValue>)或者当你想让你的对象像数组一样被使用时(例如List),就会使用它。


4
这是一个索引器,它允许对象像数组一样进行索引。
public class MyIndexer
    {
        private string[] myData;
        public string this[int ind]
        {
            get
            {
                return myData[ind];
            }
            set
            {
                myData[ind] = value;
            }
        }
    }
    
public class UseIndex
    {
        public void UseIndexer()
        {            
            MyIndexer ind = new MyIndexer();
    
            ind[1] = "Value 1";
            ind[2] = "Value 2";
            ind[3] = "Value 3";    
            ind[4] = "Value 4";    
            ind[5] = "Value 5";    
        }
    }

0

这意味着实现对象将是一个基于字符串索引的集合。例如字典。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接