在浏览我们客户的代码时,我遇到了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(); } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。