c# – 具有“this”关键字的接口成员

在浏览我们客户的代码时,我遇到了C#中的接口,它有一个带有“this”关键字的成员.
public interface ISettings
{
    string this[string key] { get; }
}

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

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#项目进行IIS部署过程中报错及其一般解决方案_c#iis执行语句...
微信扫码登录PC端网站应用的案例(C#)_c# 微信扫码登录
原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...