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

Fre*_*ong -1 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

来源

Zoh*_*led 5

这是一个索引器。

索引器允许像数组一样对类或结构的实例进行索引。无需显式指定类型或实例成员即可设置或检索索引值。索引器类似于属性,只是它们的访问器采用参数。

在本例中,该类PersonImplementsIDataErrorInfo包含一个类型为 的索引器string,它将根据您发送的任何字符串返回一个字符串 -

如果您发送它,如果年龄属性小于或大于,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"]);
Run Code Online (Sandbox Code Playgroud)

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