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

问题描述 投票:-1回答:1

此问题已经在这里有了答案:

我试图弄清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

c#
1个回答
3
投票

这是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."的结果>

© www.soinside.com 2019 - 2024. All rights reserved.