I have created a Dictionary in Application scope, but I'm not sure how to correctly access it in another page.
void Application_Start(object sender, EventArgs e)
{
Application["PaginationTable"] = new Dictionary<int, int>();
Dictionary<int, int> dictPagination = new Dictionary<int, int>();
//fill dict
for (int i = 0; i < 40; i++)
{
etc
}
Application["PaginationTable"] = dictPagination;
}
In myotherpage.cs
foreach (KeyValuePair<int, int> pair in Application["PaginationTable"])
{
Response.Write(pair.Key +" :: " + pair.Value + "<br>");
etc
}
The error generated is: "foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'"
The gist is that I need to create a Dictionary开发者_JAVA技巧 to hold a table of value/pair data that will not change and will need accessing/compared by different sections of the website.
Help appreciated
Everything stored as an Application variable (or Session varible) is of type Object.
I order to read that application variable as a Dictionary object, just cast that object to it:
foreach (var pair in (Dictionary<int, int>)Application["PaginationTable"])
As Application
can store many different types, it has to store them as Object
, the parent class all types are inherited from. You need to cast the Application["PaginationTable"]
to the correct type, i.e. Dictionary<int, int>
that foreach can operate on. i.e.:
foreach (KeyValuePair<int, int> pair in (Dictionary<int, int>)Application["PaginationTable"])
Note that to save typing KeyValuePair<int, int>
can be replaced with var
, as the compiler can work out the correct type at compile time.
Also note that the line
Application["PaginationTable"] = new Dictionary<int, int>();
is redundant as you just assign another object to it lower down.
精彩评论