c# - 如何编写一个可以用 `arr[key]` 索引的类(如数组)?

标签 c# .net arrays indexer

就像我们做的那样 Session.Add("LoginUserId", 123); 然后我们可以访问Session["LoginUserId"],就像一个数组,我们如何实现它?

最佳答案

你需要一个 indexer :

public Thing this[string index]
{
    get
    {
         // get the item for that index.
         return YourGetItemMethod(index)
    }
    set
    {
        // set the item for this index. value will be of type Thing.
        YourAddItemMethod(index, value)
    }
}

这将使您可以像使用数组一样使用您的类对象:

MyClass cl = new MyClass();
cl["hello"] = anotherObject;
// etc.

还有一个 tutorial如果您需要更多帮助,可以使用。

附录:

您提到您希望它在静态类中可用。这有点复杂,因为您不能使用静态索引器。如果你想使用索引器,你需要通过静态字段或类似 this answer 中的一些魔法来访问它。 .

关于c# - 如何编写一个可以用 `arr[key]` 索引的类(如数组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6807310/

相关文章:

c# - NUnit 无法找到程序集,但控制台应用程序可以

c# - .NET 会受益于 "named anonymous"类型吗?

javascript - 如何制作一些 HTML 单词的数组?

java - 创建其他类的数组。

c# - 对基类强制执行重写方法

c# - 如何在 C# 中将按位非运算符与移位运算符一起使用?

c# - 如何设置DataGridView的列名?

c# - 如何创建不可变类?

c# - 重载是向同一函数添加不同参数的唯一方法吗?

javascript - For循环跳过重复值