问题
Let's say I wish to store an instance of the following in Application State, to be accessed very often.
public class Example {
public string A;
public string B;
public bool C;
public int D;
// ...
}
I can't decide whether to store the whole class together as Application["Example"]
, or to store its properties individually as Application["ExampleA"]
etc.
My thinking is that ((Example)Application["Example"]).A
might have to copy the whole class into memory just to access one property - is that right? Or am I mistaken?
回答1:
I would use a static global variable, slightly better performance, type safe and will make your code easier to read. For more info see...
ASP.NET Application state vs a Static object
回答2:
you are right but....
you don't need to copy the whole object if you just need the value of one of its property. Conceptually if we are talking about a value object(you don't need an identity or a particular object) you can store just the property. If you need to know what is the value of the property for one particular object(imaging a user's password) you should store the whole object.
回答3:
The application state is stored in memory anyway so I can't see a significant overhead with retrieving the class. I'm fairly sure, although could be wrong, that the classes wouldn't be serialised/deserialised with each request.
来源:https://stackoverflow.com/questions/6857391/storing-classes-in-application-state-asp-net