如何调用这种定义属性的方式

本文关键字:定义 属性 方式 何调用 调用 | 更新日期: 2023-09-27 18:35:33

public class TestClass
{
    private Dictionary<string, int> _testDictionary = new Dictionary<string,int>();
    private string _key;
    public int this[string key]
    {
        get { return _testDictionary[key];}
        set 
        {
            if (_testDictionary.ContainsKey(key))
                _testDictionary[key] = value;
            else
                _testDictionary.Add(key, value);
        }
    }
}
public class Program
{
        static void Main(string[] args)
        {
            TestClass test = new TestClass();
            test["T1"] = 1;
            test["T2"] = 2;
            Console.WriteLine(test["T1"]);
            Console.WriteLine(test["T2"]);
        }
}

那么这种定义属性的方式是如何称呼的,我想阅读更多关于它的信息。也可以在其他地方有这样的定义,例如方法等。

如何调用这种定义属性的方式

你的实现是正确的,你可以添加你想要的索引器名称,但你不必这样做。最好从 getter 添加一个指南,以防找不到键,并返回一些默认值。

在此处查看此输入链接说明

public class TestClass
{
    private Dictionary<string, int> _testDictionary = new Dictionary<string, int>();
    // you do not need a private property to store the key
    // private string _key;
    [IndexerName("MyKeyItem")]
    public int this[string key]
    {
        get
        {
            if (_testDictionary.ContainsKey(key))
            {
                return _testDictionary[key];
            }
            return int.MinValue;
        }
        set
        {
            if (_testDictionary.ContainsKey(key))
                _testDictionary[key] = value;
            else
                _testDictionary.Add(key, value);
        }
    }
}

它被称为索引属性。