具有"this"关键字的接口成员

Ani*_*man 6 c# oop design-patterns interface

在浏览我们客户的代码时,我遇到了C#中的接口,它有一个带有"this"关键字的成员.

 public interface ISettings
{
    string this[string key] { get; }
}
Run Code Online (Sandbox Code Playgroud)

我不知道接口成员名称以"this"开头的任何此类模式或实践.为了解更多,我检查了这个接口的实现,但仍然无法弄清楚它的用途.

internal class SettingsManager : ISettings
{
    public string this[string key]
    {
        get { return ConfigurationManager.AppSettings[key]; }
    }
   ...
   ...
}
Run Code Online (Sandbox Code Playgroud)

这是调用者代码:

public static class Utility
{
   public static ISettings Handler { get; set; }

    public static string Get(string key, string defaultValue)
    {
        var result = Handler[key];

        return Is.EmptyString(result) ? defaultValue : result;
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我无法调试此代码以查看实时内容.但对此非常好奇.如果实现的代码最终返回一个字符串,那么"this"关键字的用途是什么?

rhu*_*hes 5

它使您能够执行以下操作:

SettingsManager settings = new SettingsManager();
var setting = settings["my setting"];
Run Code Online (Sandbox Code Playgroud)

一个常见的用途是与List<T>班级.

它有定义:

public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
{
    // ....

    public T this[int index] { get; set; }

    // ....
}
Run Code Online (Sandbox Code Playgroud)

这允许您以与数组类似的方式"索引"内部值.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace test
{
    static class Program
    {
        static void Main()
        {
            List<string> myStrings = new List<string>();

            myStrings.Add("abc");
            myStrings.Add("def");

            Console.WriteLine(myStrings[0]); // outputs: "abc"
            Console.WriteLine(myStrings[1]); // outputs: "def"

            Console.Read();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


jno*_*ovo 5

它们是索引器,允许像数组一样访问您的类,在您提供的示例中,您可以看到此行中的用法:

var result = Handler[key];
Run Code Online (Sandbox Code Playgroud)