有人可以解释Connection是如何工作的吗?它的返回类型是Interface IDataConncecton。 GlobleConfig类正在创建一个SqlConnector类型的对象,该对象实现IDataConnection,然后将对象分配给Connection属性。
公共静态类GlobalConfig {
***public static IDataConnection Connection { get; private set; }***
public static void InitializeConnection(DatabaseType db)
{
if(db == DatabaseType.Sql)
{
// Create the SQL Connection
SqlConnector sql = new SqlConnector();
Connection= sql;
}
else if (db == DatabaseType.TextFile)
{
// Create the test connction
TextConnector text = new TextConnector();
Connection= text;
}
}
public static string CnnString(string name)
{
//will go to App.Config to get connectionString using name tag
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
接口实施
public class SqlConnector : IDataConnection
{
public PersonModel CreatePerson(PersonModel model)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString("Tournaments")))
{
var p = new DynamicParameters();
p.Add("@FirstName", model.FristName);
p.Add("@LastName", model.LastName);
p.Add("@EmailAdress", model.EmailAddress);
p.Add("@CellphoneNumber", model.CellphoneNumber);
p.Add("@id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Execute("dbo.spPeople_Insert", p, commandType: CommandType.StoredProcedure);
model.Id = p.Get<int>("@id");
return model;
}
}
}
接口实现 公共类TextConnector:IDataConnection { 私有const字符串PrizesFile =“PrizeModels.csv”;
public PersonModel CreatePerson(PersonModel model)
{
List<PersonModel> people = PrizesFile.FullFilePath().LoadFile().ConvertToPersonModels();
int currentId = 1;
if (prizes.Count > 0)
{
currentId = prizes.OrderByDescending(x => x.Id).First().Id + 1;
}
model.Id = currentId;
prizes.Add(model);
}
}
答案 0 :(得分:0)
C#中的接口声明了实现它的类应该支持和提供公共成员。目标是描述类可以做什么。接口本身没有实现。
在代码中使用接口的原因(特别是在构造函数和方法参数中)而不是类,是为了使代码更灵活,可维护和可测试。如果您想从SQL Server切换到MySQL或SQLite,您所要做的就是提供一个实现IConnection
接口的类。您当然可以将具体类型的实例存储到它实现的接口类型的属性中。这样,用户可以看到界面提供的内容,但不会看到具体类的其他成员。
使用接口而不是具体类也会使您的代码更易于测试,因为您可以对接口进行模拟实现,并将它们替换为真正的类,以便能够隔离测试的代码。 / p>
针对接口进行编程是面向对象编程的基本原则之一,从长远来看,证明非常有用,需求一直在变化:-)。