如何编写一个可以用“arr[key]”索引的类(如数组)?
就像我们做的那样 Session.Add("LoginUserId", 123);
然后我们就可以访问Session["LoginUserId"]
,就像一个Array一样,我们如何实现呢?
Like we do Session.Add("LoginUserId", 123);
and then we can access Session["LoginUserId"]
, like an Array, how do we implement it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要一个索引器:
这将允许您像使用类对象一样使用类对象数组:
还有一个 教程。
附录:
您提到您希望在静态类上使用它。这个有点复杂,因为你不能使用静态索引器。如果您想使用索引器,则需要从静态字段或诸如
You need an indexer:
This will let you use your class objects like an array:
There's also a tutorial available if you need more help.
Addendum:
You mention that you wanted this to be available on a static class. That get's a little more complicated, because you can't use a static indexer. If you want to use an indexer, you'd need to access it off of a static Field or some such sorcery as in this answer.
您应该使用索引器
请参阅链接:
http://msdn.microsoft.com/en-us/library/2549tw02.aspx
You should use indexers
See the link:
http://msdn.microsoft.com/en-us/library/2549tw02.aspx
听起来您需要的只是一个通用字典。
如果您想使其静态,只需将其设为另一个类中的静态成员即可。
然后您可以这样访问它,而无需初始化它:
如果您想要更具冒险精神并且正在使用 .NET 4,您还可以使用 Expando 对象,类似于 ASP.NET MVC 3 中控制器可用的 ViewBag 成员:
Sounds like all you need is a generic dictionary.
If you want to make this static, just make it a static member in another class.
Then you can access it as such, without having to initialize it:
If you want to be more adventurous and are using .NET 4 you can also use an Expando Object, like the ViewBag member available to controllers in ASP.NET MVC 3:
按照您通常使用会话变量的方式,您真正需要的是 像这样的通用词典集合。你真的不需要写一个类。但是,如果您需要添加额外的功能和/或语义,您当然可以用一个类包装集合,然后只包含和索引器。
对于其他集合,请查看 Collections.Generic 命名空间。
With the way you usually use the Session variable all you really need is a generic Dictionary collection like this one. You don't really need to write a class. But if you need to add extra functionality and/or semantics you could certainly wrap the collection with a class and just include and indexer.
For other collections check out the Collections.Generic namespace.