我有这样的代码:
public string ReadName(int ID)
{
if(db.Name == "mysql") return mysql.ReadName(ID);
else if(db.Name == "oracle") return oracle.ReadName(ID);
}
我有很多这样的功能。 有没有办法我不能在每个函数中重复if-else?
谢谢
答案 0 :(得分:4)
您可以定义一个界面:
public interface IMyDb
{
string ReadName(int ID);
}
然后让每个特定于数据库的类实现它:
public class MySqlDb : IMyDb
{
public string ReadName(int ID)
{
// you have already written the code for this method
}
}
然后,当您的应用程序初始化时,您只需一个开关:
IMyDb dbImpl;
switch (db.Name)
{
case "mysql":
dbImpl = new MySqlDb();
break;
case "oracle":
...
}
最后,您可以调用该方法,而无需担心您在引擎盖下使用哪个类:
string name = dbImpl.ReadName(23);
答案 1 :(得分:0)
继承:
答案 2 :(得分:0)
**编辑:我在看到有人回答之前写过这篇文章......任何方式这只是一个小小片段的想法**
首先,如果您不了解OOP优点和继承,则无法解决此问题。如果oracle和mysql继承自相同的泛型类型(类或接口),则可以使用多态。最好的选择是保持对正确数据库的引用,并在构造函数中初始化它。
public interface DbInterface {
... Generic method declaration
}
public class Mysql :db {
... Generic method implementation
}
public class Oracle :db {
... Generic method implementation
}
public class YourClass {
private DbInterface _db;
public YourClass(DbInterface db) {
this._db = db;
}
}
然后每次使用_db时,您都知道它是您想要的数据库。