就像我们做的那样 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/