Like we do Session.Add("LoginUserId", 123);
and then we can access Session["LoginUserId"]
, like an Array, how do we implement it?
问题:
回答1:
You need an 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)
}
}
This will let you use your class objects like an array:
MyClass cl = new MyClass();
cl["hello"] = anotherObject;
// etc.
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.
回答2:
You should use indexers See the link: http://msdn.microsoft.com/en-us/library/2549tw02.aspx
回答3:
Sounds like all you need is a generic dictionary.
var session = new Dictionary<string, object>();
//set value
session.Add("key", value);
//get value
var value = session["key"] as string;
If you want to make this static, just make it a static member in another class.
public static class SharedStorage
{
private static Dictionary<string, object> _data = new Dictionary<string,object>();
public static Dictionary<string, object> Data { get { return _data; } }
}
Then you can access it as such, without having to initialize it:
SharedStorage.Data.Add("someKey", "someValue");
string someValue = (string) SharedStorage.Data["someKey"];
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:
dynamic expando = new ExpandoObject();
expando.UserId = 5;
var userId = (int) expando.UserId;
回答4:
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.