Can I use a class as an object in .NET to create instances of that class?
I'm writing a fairly uncomplicated program which can "connect" to several different types of data sources including text files and various databases. I've decided to implement each of these connection types as a class inherited from an interface I called iConnection. So, for example, I have TextConnection, MySQLConnection, &c... as classes.
In another static class I've got a dictionary with 开发者_运维技巧human-readable names for these connections as keys. For the value of each dictionary entry, I want the class itself. That way, I can do things like:
newConnection = new dict[connectionTypeString]();
Is there a way to do something like this? I'm fairly new to C# so I'd appreciate any help.
I assume you realize that the .NET Framework already has an IDbConnection interface and corresponding implementors that already do most of what you seem to be trying to do?
In any case, what you're looking for is the Factory Method Pattern. A factory method is a method that is responsible for creating concrete instances of a specific interface based on a user-supplied type parameter (usually an enumeration).
There's a C# example here, although there are many different ways to implement the pattern.
another variation on factory pattern. just maintain a list of types:
Dictionary<string, Type> pizzas = new Dictionary<string, Type>
{
{ "HamAndMushroomPizza", typeof(HamAndMushroomPizza) },
{ "DeluxePizza", typeof(DeluxePizza) },
{ "HawaiianPizza", typeof(HawaiianPizza) }
};
then to create concrete instances:
string pizzaName = Console.ReadLine();
IPizza p = (IPizza)Activator.Create(pizzas[pizzaName]);
Console.WriteLine("{0}'s Price: {1}", pizzaName, p.Price);
the attractiveness of this approach is when you cannot determine in advance how many pizza varieties you can have, you cannot afford to rewrite your pizza factory(switch statements) every time there's new type of pizza(think of loading DLLs at runtime)
Look at the DbProviderFactory class in the System.Data.Common namespace. You can use it to create connections, commands, data adapters, etc., for a given provider. Example:
DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
DbConnection connection = factory.CreateConnection();
Where providerName is something like "System.Data.SqlClient" or "System.Data.OleDb", etc.
Go check out StructureMap. You can do some really cool DI with that or some of these other alternatives.
精彩评论