我有很多方法在大部分的後面跟着相同的算法,我理想地希望能夠調用一個消除大量代碼重複的泛型方法。有大量代碼重複的問題
我有一大堆像下面的那些方法,我會最佳希望能夠只是調用 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'移出方法並將其作爲參數傳遞,那麼我相信您可以使其他代碼通用。 – 2014-12-04 20:01:28
您是否考慮過尋找表達式樹來構建「查找」聲明? –
2014-12-04 20:02:23
'storedX'或者是null,所以不需要使用else if。由於這個原因,你永遠不會返回false,所以你可以刪除返回值。左邊是'if(storedX!= null){dbConn.Update(itemToSave); } else {dbConn.Insert(itemToSave); primaryKey = itemToSave.PrimaryKey; }'。刪除了3行 – Default 2014-12-04 20:17:21