【发布时间】:2014-12-04 19:49:47
【问题描述】:
我有很多方法在很大程度上遵循相同的算法,理想情况下,我希望能够调用通用方法,从而消除大量代码重复。
我有很多像下面这样的方法,我希望能够只调用
Save<SQLiteLocation>(itemToSave); 但我遇到了很多麻烦,因为这些方法
SQLiteConnection.Find<T> 在泛型中不接受像 T 这样的抽象数据类型。
有什么办法可以解决这个问题,如果我能修复它,我会节省多达 150 行代码
这是我的代码:
public bool SaveLocation(ILocation location, ref int primaryKey)
{
var dbConn = new SQLiteConnection (dbPath);
SQLiteLocation itemToSave = new SQLiteLocation ();
itemToSave.LocationName = location.LocationName;
itemToSave.Latitude = location.Latitude;
itemToSave.Longitude = location.Longitude;
itemToSave.PrimaryKey = location.PrimaryKey;
----------------------------------------------------------------------------------------
SQLiteLocation storedLocation = dbConn.Find<SQLiteLocation>
(x => x.PrimaryKey == location.PrimaryKey);
if (storedLocation != null)
{
dbConn.Update(itemToSave);
return true;
}
else if (storedLocation == null)
{
dbConn.Insert(itemToSave);
primaryKey = itemToSave.PrimaryKey;
return true;
}
return false;
}
这里还有另一种方法,看看我的虚线下面的两种方法中的代码基本上是一样的
public bool SaveInvitation(IInvitation invitation, ref int primaryKey)
{
var dbConn = new SQLiteConnection(dbPath);
SQLiteInvitation itemToSave = new SQLiteInvitation ();
itemToSave.GroupName = invitation.GroupName;
itemToSave.InviterName = invitation.InviterName;
itemToSave.ParseID = invitation.ParseID;
itemToSave.GroupParseID = invitation.GroupParseID;
itemToSave.PrimaryKey = invitation.PrimaryKey;
---------------------------------------------------------------------------------------
SQLiteInvitation storedInvitation = dbConn.Find<SQLiteInvitation>
(x => x.PrimaryKey == invitation.PrimaryKey);
if (storedInvitation != null)
{
dbConn.Update(itemToSave);
return true;
}
else if (storedInvitation == null)
{
dbConn.Insert(itemToSave);
primaryKey = itemToSave.PrimaryKey;
return true;
}
return false;
}
【问题讨论】:
-
您可以使用 AutoMapper 或类似的东西来移动属性。另外,如果您将
itemToSave移出方法并将其作为参数传递,那么我相信您可以使其余代码通用。 -
您是否考虑过研究表达式树来构建
Find<T>语句? -
storedX要么是null,要么不是,所以不需要使用else if。因此,您永远不会返回 false,因此您可以删除返回值。左边是if(storedX != null){ dbConn.Update(itemToSave); } else{ dbConn.Insert(itemToSave); primaryKey = itemToSave.PrimaryKey; }。在那里删除了 3 行 -
我会研究 AutoMapper 和 Expression 树,虽然我不熟悉它,但我会研究它,谢谢您的输入。是的,你是对的,它总是为空或不为空,谢谢
标签: c# generics android-sqlite maintainability