kei*_*kei 7 c# generics ado.net
我有两个类似的方法,基本上只用不同的对象做同样的事情.如果可能的话,用这种方法制作通用方法的最佳方法是什么?
这两个对象:
public class StoreObject {
int Key;
string Address;
string Country;
int Latitude;
int Longitude;
}
public class ProjectObject {
int ProjectKey;
string Address;
string Description;
}
Run Code Online (Sandbox Code Playgroud)
我可能希望将这两种方法变成泛型:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我必须注意:
- 我无法控制表字段的命名方式(即.p_description).
例如,DB中的StoreTable可能有其他属性(如电话,邮政编码等),但我只想展示我在代码中显示的内容.
- ProjectTable也是如此.
好吧,棘手的部分是您的实体具有不同的属性,因此使用泛型在一个方法中填充不同的属性是不值得的。但是您可以返回整个对象,然后只使用您感兴趣的属性。
public T GetEntityByKey<T>(int key)
{
using (DBEntities dbe = new DBEntities())
{
return = dbe.StoreTables.Set<T>.Find(new object[] {key});
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它
StoreObject so = GetEntityByKey<StoreObject>(123);
if(so != null)
{
int lat = so.Latitude;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
311 次 |
最近记录: |