大家好,我是一个C#初学者,遇到如下问题,请求帮助:
如:
namespace test
{
//接口的定义
public interface IsServer {
bool GetDataTable(string User, string strsql); bool ExcuteSql(string User, DataTable dt);
} //接口的实现
public class SqlServer : IsServer
{
private SqlDB nn = new SqlDB();
DataTable IsServer.GetDataTable(string User, string strsql)
{
return true;
} bool IsServer.ExcuteSql(string User, DataTable dt)
{
return true;
}
}
//接口的调用
public class CallInterface
{
//请问是不是这样调用的啊,是否还有别的方法去调用呢,如果只能这样调用的话,
//那为什么还要用到接口呢,而不直接定义类实例去调用呢?
private IsServer TestInterface = new SqlServer();
}
}// end test
如:
namespace test
{
//接口的定义
public interface IsServer {
bool GetDataTable(string User, string strsql); bool ExcuteSql(string User, DataTable dt);
} //接口的实现
public class SqlServer : IsServer
{
private SqlDB nn = new SqlDB();
DataTable IsServer.GetDataTable(string User, string strsql)
{
return true;
} bool IsServer.ExcuteSql(string User, DataTable dt)
{
return true;
}
}
//接口的调用
public class CallInterface
{
//请问是不是这样调用的啊,是否还有别的方法去调用呢,如果只能这样调用的话,
//那为什么还要用到接口呢,而不直接定义类实例去调用呢?
private IsServer TestInterface = new SqlServer();
}
}// end test
{
//接口的定义
public interface IsServer {
bool GetDataTable(string User, string strsql); bool ExcuteSql(string User, DataTable dt);
} //接口的实现
public class SqlServer : IsServer
{
private SqlDB nn = new SqlDB();
DataTable IsServer.GetDataTable(string User, string strsql)
{
return true;
} bool IsServer.ExcuteSql(string User, DataTable dt)
{
return true;
}
}
//接口的实现
public class OracleServer : IsServer
{
private SqlDB nn = new SqlDB();
DataTable IsServer.GetDataTable(string User, string strsql)
{
return true;
} bool IsServer.ExcuteSql(string User, DataTable dt)
{
return true;
}
}
//接口的调用
public class CallInterface
{
//请问是不是这样调用的啊,是否还有别的方法去调用呢,如果只能这样调用的话,
//那为什么还要用到接口呢,而不直接定义类实例去调用呢?
private IsServer TestInterface = new SqlServer();
private IsOracleServer Interface = new OracleServer();
}
}// end test
你的程序里面的功能方法等等都已经写好了
这个时候用户突然想把数据库换成是oracle的
oracle的操作数据库和sql的又不太一样
这个时候你只需要写一个操作oracle的类就可以。
1.直接实例化实现了接口的类,如IUser user = new User();
2.服务定位器Service Locator;
3.依赖注入IoC。
当然,设计模式里的创建型模式很多都是解决接口的调用问题的。
后两种可以看这篇文章:
IoC容器和依赖注入模式
接口实现:DataTable IsServer.GetDataTable(string User, string strsql)楼主确定程序没出错?
DataTable IsServer.GetDataTable(string User, string strsql)
没有实现接口里的方法,实现方法的签名应与接口里定义的签名一样
public bool IsServer.GetDataTable(string User, string strsql)
1.抽象和实现分离
2.实现多态
LZ用的显示实现接口的办法只能通过接口的引用调用不能用类的实例直接调用。
IsServer.GetDataTable返回类型应为bool。