Is it possible to populate a lookup table at Compile Time? C#
I have a somewhat sizeable Hashtable populated with lookup only static data.
This means that when the program starts, I'll either have a long initializer/constructor method that will execute many hashtable.Add() methods (yuk) or de-serialize开发者_运维知识库 from a resource file that I've custom generated at coding time.
Is there an attribute or another way I could use to include this data at compile-time?
If your data is strictly static (or static enough that you can hard-code it in your program), then you could just put all of your values in a switch statement. Can't really say if it is a good idea or not, but it doesn't seem any worse than loading up a HashTable. On the plus side, the "hash table" initialization does become a strictly compile time operation:
public int Lookup(int key)
{
switch (key)
{
case K1: return V1;
case K2: return V2;
case K3: return V3;
case K4: return V4;
case K5: return V5;
case K6: return V6;
case K7: return V7;
default: return V_WHOOPS;
}
}
If the number of values is large, you could write a script to generate the code rather than type it in by hand.
Depending on what you have in the table. You can always use a resource file.
http://msdn.microsoft.com/en-us/library/ekyft91f.aspx
Theres no way to conceptually setup an object at compile time. The object must be allocated/constructed by .NET runtime then filled out with data somehow.
As far as how do you make this faster, you could try serializing the Hashtable to a binary file after all the slow Add calls have been made on it.
Then in your main application you can just serialize it back when it needs it.
This would hopefully give you faster initialization of your HashTable as opposed to many .Add calls.
If you want an instance of HashTable at run-time, you must allocate and populate that instance of HashTable at run-time.
If you want to make a decision with a value, you could write a method.
A way you could handle this, if you don't want to load a Hashtable at runtime is to store the data in a database and then perform a lookup either with queries or LINQ. There are several options out there, SQLLite , SqlServerCE if you just want something desktop oriented. You could also use something more robust like SqlServer or MySql depending on the scope of your application.
精彩评论