|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Dynamically instance a classI have a setting in my database where the user specifies a tax configuration (e.g. "UK/EU") and I have several tax classes that handle these
different configurations. So what is the best way to instance the proper class based on what is in this configuration parameter. I could use a simple switch statement but it seems like there should be a better way. >I have a setting in my database where the user specifies a tax configuration (e.g. "UK/EU") and I have several tax classes that handle these You could store the corresponding type name in a table (either in the>different configurations. So what is the best way to instance the proper class based on what is in this configuration parameter. I could use a >simple switch statement but it seems like there should be a better way. database or in your code, e.g. a hashtable) and use that create the right type of object. The System.Type.GetType and System.Activator.CreateInstance methods may be helpful. Mattias -- Mattias Sjögren [C# MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com Please reply only to the newsgroup. "APA" <buddy***@hotmail.com> wrote in message Store the full name of the class in your database (perhaps in a table of news:e2S%23PbP3GHA.4312@TK2MSFTNGP02.phx.gbl... >I have a setting in my database where the user specifies a tax >configuration (e.g. "UK/EU") and I have several tax classes that handle >these different configurations. So what is the best way to instance the >proper class based on what is in this configuration parameter. I could use >a simple switch statement but it seems like there should be a better way. it's own with a small surrogate key in your other tables). Then use Type.GetType(typeName) to get the type, and Activator.CreateInstance(yourType) to create an instance of the class. If you need to pass in constructor parameters, you can use Type.GetConstructor() to get a ConstructorInfo object, then use ConstructorInfo.Invoke() to instantiate the type, passing in your constructor parameters. -cd |
|||||||||||||||||||||||