我有两个类似的方法,基本上只是使用不同的对象来完成相同的事情。 如果可能的话,如何将它们制作成通用方法?
这两个对象:
public class StoreObject {
int Key;
string Address;
string Country;
int Latitude;
int Longitude;
}
public class ProjectObject {
int ProjectKey;
string Address;
string Description;
}
我希望将以下两种方法转化为通用方法:
public StoreObject GetStoreByKey(int key)
{
using (DBEntities dbe = new DBEntities())
{
StoreObject so = new StoreObject();
var storeObject = (from s in dbe.StoreTables
where s.Key == key
select s).First();
so.Key = storeObject.key;
so.Address = storeObject.address;
so.Country = storeObject.country;
so.Latitude = storeObject.latitude;
so.Longitude = storeObject.longitude;
return so;
}
}
public ProjectObject GetProjectByKey(int projectKey)
{
using (DBEntities dbe = new DBEntities())
{
ProjectObject po = new ProjectObject();
var projectObject = (from p in dbe.ProjectTables
where p.ProjectKey == projectKey
select p).First();
po.Key = projectObject.p_key;
po.Address = projectObject.p_address;
po.Description = projectObject.p_description;
return po;
}
}
我必须说明以下几点:
- 我无法控制表格字段的命名方式(例如p_description)。
- 数据库中的StoreTable可能有其他属性(例如电话、邮政编码等),但我只对代码中显示的内容感兴趣。
- ProjectTable也是如此。