我有两种类似的方法,它们基本上只对不同的对象做同样的事情。如果可能的话,从中制作通用方法的最佳方法是什么?
两个对象:
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 也是如此。