我可以使用类作为 .NET 中的对象来创建该类的实例吗?
我正在编写一个相当简单的程序,它可以“连接”到几种不同类型的数据源,包括文本文件和各种数据库。我决定将每种连接类型实现为从我称为 iConnection 的接口继承的类。因此,例如,我有 TextConnection、MySQLConnection、&c... 作为类。
在另一个静态类中,我有一个字典,其中包含这些连接的人类可读名称作为键。对于每个字典条目的值,我想要类本身。这样,我就可以做这样的事情:
newConnection = new dict[connectionTypeString]();
有没有办法做这样的事情?我对 C# 相当陌生,因此我将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我假设您意识到 .NET Framework 已经有一个 IDbConnection< /a> 接口和相应的实现器已经完成了您似乎正在尝试做的大部分事情?
无论如何,您要寻找的是工厂方法模式。工厂方法是一种负责根据用户提供的类型参数(通常是枚举)创建特定接口的具体实例的方法。
尽管有许多不同的方法来实现该模式,但这里有一个 C# 示例。
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.
工厂模式的另一种变体。只需维护一个类型列表:
然后创建具体实例:
这种方法的吸引力在于,当您无法提前确定可以拥有多少种披萨品种时,您无法在每次有新类型时重写您的披萨工厂(switch 语句)披萨(考虑在运行时加载 DLL)
another variation on factory pattern. just maintain a list of types:
then to create concrete instances:
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)
查看 System.Data.Common 命名空间中的 DbProviderFactory 类。您可以使用它为给定的提供程序创建连接、命令、数据适配器等。示例:
providerName 类似于“System.Data.SqlClient”或“System.Data.OleDb”等。
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:
Where providerName is something like "System.Data.SqlClient" or "System.Data.OleDb", etc.
去看看 StructureMap。您可以使用它或一些其他替代方案进行一些非常酷的DI。
Go check out StructureMap. You can do some really cool DI with that or some of these other alternatives.