如何重写基类?数据库连接字符串?

发布于 2024-11-30 09:22:45 字数 155 浏览 2 评论 0原文

我有一个基类(使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独享拥抱 2024-12-07 09:22:45

我建议为您的类提供一个重载的构造函数,如下所示:

private readonly string connectionString;

public Foo() : this(Settings.Default.DbConnectionString) {
}

public Foo(string connectionString) {
    this.connectionString = connectionString;
}

然后派生类可以将“重写”连接字符串传递到构造函数中。

我认为这比使用虚拟属性等的多态性更干净 - 特别是因为连接字符串在对象的生命周期中不会改变。您并没有真正改变行为(这就是多态性的好处) - 您只是改变了初始化(这就是构造函数参数的好处)。

I would suggest giving your class an overloaded constructor, like this:

private readonly string connectionString;

public Foo() : this(Settings.Default.DbConnectionString) {
}

public Foo(string connectionString) {
    this.connectionString = connectionString;
}

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).

↘紸啶 2024-12-07 09:22:45

使连接字符串成为基类中受保护的虚拟属性

class Base {
    protected virtual string ConnectionString { get { ... } } // Get from config.
}

class Sub {
    protected override string ConnectionString { get { ... } } // return the new value.
}

Make the connection string a protected virtual property in your base class

class Base {
    protected virtual string ConnectionString { get { ... } } // Get from config.
}

class Sub {
    protected override string ConnectionString { get { ... } } // return the new value.
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文