C# this[] 括号构造函数

本文关键字:构造函数 this | 更新日期: 2023-09-27 18:37:03

我在另一个库中发现您可以使用各种参数调用类实例...

他们使用this[int y, int z]格式。

我试图复制它,但我在任何 C# 网站中都找不到任何东西。

class xx
    {
        private int _y { get; private set; }
        private int _z { get; private set; }
        public xx this[int y, int z] { get; set; }
        public xx(int y, int z){
            _y = y;
            _z = z;
        }
    }

    xx z = new xx(1, 2);
    xx y = xx[1, 2];

我正在尝试弄清楚如何使用这种this[options]格式。(上面的代码是完全错误的)

这样

,不必每次都建立新实例会更容易。

而不是去:

Column y = new Column(1, "value", "attributes;attribute;attribute");
FullTable.Add(y);

我可以做:

FullTable.Column[1, "value", "attributes;attribute;attribute"]; // can get the instance or create it.

它已经被实例化了,一切都被实例化了。

无论如何,OOP大师会如何做到这一点?有什么想法吗?

C# this[] 括号构造函数

它称为索引器,用于引用类中的项。

例如,假设您要编写一个程序来组织您的 DVD 电影收藏。你可以有一个构造函数来创建要放入集合中的 DVD 电影,但通过索引器允许的 ID "获取"DVD 电影会很有用。

public class MovieCollection
{
    private Dictionary<string, Movie> movies = 
               new Dictionary<string, string>(); 
    private Dictionary<int, string> moviesById = 
               new Dictionary<int, string>();
    public MovieCollection()
    {
    }
    // Indexer to get movie by ID
    public Movie this[int index]  
    {
        string title = moviesById[index];
        return movies[title];
    }
}

this[int x]语法称为索引器。这是你如何实现数组、列表和字典中使用的那种东西,让你做,例如 myList[0] .它不能用作构造函数,您应该只使用您已经知道的普通构造函数语法。