如何重写基类?数据库连接字符串?
我有一个基类(使用 C#.net 编写),它使用数据集从数据库中提取数据,连接字符串位于 App.config 文件中。所以写完基类后它就被编译成dll了。
要在不同的项目中使用这个基类,我必须覆盖数据库连接字符串,所以首先可以这样做吗?如果可能的话,任何人都可以给我一个例子吗?
I have a base class (written using C#.net) which uses datasets to pull data from DB and the connection string is in App.config file. So after writing the base class it has been compiled into dll.
And to use this base class for different project I have to override the DB connection string, so first is it possible to do and if possible, can anyone give me an example for it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议为您的类提供一个重载的构造函数,如下所示:
然后派生类可以将“重写”连接字符串传递到构造函数中。
我认为这比使用虚拟属性等的多态性更干净 - 特别是因为连接字符串在对象的生命周期中不会改变。您并没有真正改变行为(这就是多态性的好处) - 您只是改变了初始化(这就是构造函数参数的好处)。
I would suggest giving your class an overloaded constructor, like this:
Then the derived class can just pass the "overridden" connection string into the constructor.
I think this is cleaner than using polymorphism with a virtual property etc - especially as presumably the connection string isn't going to change over the course of the object's lifetime. You're not really changing the behaviour (which is what polymorphism's good for) - you're changing the initialization (which is what constructor parameters are good for).
使连接字符串成为基类中受保护的虚拟属性
Make the connection string a protected virtual property in your base class