加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:29:05 所属栏目:百科 来源:网络整理
导读:在浏览我们客户的代码时,我遇到了C#中的接口,它有一个带有“this”关键字的成员. public interface ISettings{ string this[string key] { get; }} 我不知道接口成员名称以“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();
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读