如何动态实例化3个不同的类到同一个变量名中,linq2sql c#
假设我的数据库中有 3 个表:人员、任务和项目
假设我有 3 个存储库类:PeopleRepository、TaskRepository 和 ProjectRepository。
现在我想要一个可以与这些类中的任何一个一起使用的方法。
显然,我可以为每个表编写大量代码,但我宁愿将代码减少到最少。对于可能传递给该方法的不同列名称,我已经有反射工作正常,但我似乎无法让这样的代码工作。
switch (tableName)
{
case "people":
var repository = new PeopleRepository();
break;
case "tasks":
var repository = new TaskRepository();
break;
case "projects":
var repository = new ProjectRepository();
break;
}
//Modify respective database table
repository.getItem(id); //etc
repository.Save(); //etc
我尝试过其他一些类似的方法,但似乎都不起作用。更改变量定义的范围等。
我觉得 c# 应该有一些很好的东西来处理这个问题,是这样吗?或者我必须在每个 switch 语句中编写相同的代码?
Say I have 3 tables in my database: people, tasks and projects
Say I have 3 classes for repository's: PeopleRepository, TaskRepository and ProjectRepository.
Now I want a single method, that will work with any of these classes.
Obviously I could just write out loads of code for each table, but I'd rather keep code down to a minimum. I already have reflection working fine for the different column names that might be passed to the method, but I can't seem to get code like this to work.
switch (tableName)
{
case "people":
var repository = new PeopleRepository();
break;
case "tasks":
var repository = new TaskRepository();
break;
case "projects":
var repository = new ProjectRepository();
break;
}
//Modify respective database table
repository.getItem(id); //etc
repository.Save(); //etc
I've tried a few other things like this, but none of them seemed to work. Changing the scope of where the variable is defined etc.
I feel like c# should have something nice to deal with this, is this so? Or do I have to write the same code in each switch statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建一个这些类将实现的接口。然后使用
您还可以使存储库
动态
并且类型将在运行时解析。
You could make an interface that those classes would implement. Then use
You can also make repository
dynamic
And the type will be resolved in runtime.
使用 .getItem(id) 和 .Save() 的虚拟方法创建一个父类 (RepositoryBase),从其继承,并在 PeopleRepository、TaskRepository 和 ProjectRespository 的每个实现中重写这些方法。
另一个选项是创建一个所有三个都可以使用的接口 (IRepository)。
Create a parent class (RepositoryBase) with virtual methods for .getItem(id) and .Save(), inherit from it, and override those methods in each implementation for PeopleRepository, TaskRepository, and ProjectRespository.
The other option is to create an interface (IRepository) that all three can use.