“ this [string name]”在声明中是什么意思:“ public string this [string name]”

时间:2019-11-19 09:17:42

标签: c#

我正在尝试弄清this [string name]在声明public string this[string name]中的含义

完整代码:

public class PersonImplementsIDataErrorInfo : IDataErrorInfo
{
    private int age;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Error
    {
        get
        {
            return "";
        }
    }

    public string this[string name]
    {
        get
        {
            string result = null;

            if (name == "Age")
            {
                if (this.age < 0 || this.age > 150)
                {
                    result = "Age must not be less than 0 or greater than 150.";
                }
            }
            return result;
        }
    }
}

Source

1 个答案:

答案 0 :(得分:4)

这是indexer.

  

索引器允许类或结构的实例像数组一样被索引。无需显式指定类型或实例成员即可设置或检索索引值。索引器类似于属性,不同之处在于它们的访问器带有参数。

在这种情况下,PersonImplementsIDataErrorInfo类包含类型为string的索引器,它将根据您发送的任何字符串返回一个字符串-

如果您发送Age,如果age属性小于null或大于"Age must not be less than 0 or greater than 150.",它将返回0150

考虑以下代码:

var person = new PersonImplementsIDataErrorInfo() { Age = 167 };

Console.WriteLine(person["Something"]);
Console.WriteLine(person["Age"]);

这将导致一个空白行(因为Something将返回一个空字符串)和一行读取"Age must not be less than 0 or greater than 150."