c# - 带有 "this"关键字的接口(interface)成员

标签 c# oop design-patterns interface

在检查我们客户的代码时,我在 C# 中遇到了以下接口(interface),它有一个带有“this”关键字的成员。

 public interface ISettings
{
    string this[string key] { get; }
}

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

internal class SettingsManager : ISettings
{
    public string this[string key]
    {
        get { return ConfigurationManager.AppSettings[key]; }
    }
   ...
   ...
}

调用者代码如下:

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;
    }
}

不幸的是,我无法调试此代码以查看实际情况。但是对它很好奇。如果实现的代码最终返回一个字符串,那么“this”关键字有什么用?

最佳答案

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

SettingsManager settings = new SettingsManager();
var setting = settings["my setting"];

一个常见的用法是使用 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; }

    // ....
}

这允许您以类似于数组的方式“索引”内部值。

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();
        }
    }
}

关于c# - 带有 "this"关键字的接口(interface)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21404645/

相关文章:

c# - C# 中的聚合与继承,或替代方案

mysql - 在 MySQL 中使用变量赋值从最后一行减去值

c# - 如何将 ASP.NET Web API 请求正文记录到 Application Insights 失败中?

c++ - 访问指定为私有(private)的基类的公共(public)静态成员

c# - 在 .Net WPF/DirectX 中显示视频信号

java - Activity 是 MainFragmentListener 的实例,是真的吗?

design-patterns - 工厂方法是哪个方法

c# - 命名空间和类名指南

c# - Unity3D - 通过单击对象将其移动到相反方向

c# - 使用 EnvDte 迭代类成员时跳过私有(private)属性