剛剛發現有點代碼這裏有人寫訪問某些數據庫實體...使用`其中T:SOMETHING`構建C#
public static OurCustomObject GetOurCustomObject(int primaryKey)
{
return GetOurCustomObject<int>(primaryKey, "usp_GetOurCustomObjectByID");
}
public static OurCustomObject GetOurCustomObject(Guid uniqueIdent)
{
return GetOurCustomObject<Guid>(uniqueIdent, "usp_GetOurCustomObjectByGUID");
}
private static OurCustomObject<T>(T identifier, string sproc)
{
if((T != typeof(int)) && (T == typeof(Guid)))
{
throw new ArgumentException("Identifier must be a string or an int");
}
//ADO.NET Code to make DB Call with supplied sproc.
}
的Theres只是一些事情似乎並不很generic
。 sprocs傳入內部方法的事實感覺很難看。但我周圍看到的唯一途徑是的if/else沿的
if(type == int)
sproc = "GetByID";
else if (type == Guid)
sproc = "GetByGUID";
行私有方法同樣的異常拋出長相醜陋也有一個......反正是有使用其中T :子句
例如
private static OurCustomObject<T>(T identifier) where T : int OR Guid
有關如何清理這一點的任何建議。
你在方法的機身採用「T」的呢? – 2009-06-04 15:36:03
就是這樣,它並沒有被專門使用。有typeof(T)== typeof(int)檢查,然後他們只是使用SQL Helper調用執行SPROC,並將標識符作爲參數傳遞。這就是爲什麼我只是覺得用法感覺有點被迫 – 2009-06-04 18:33:51
然後我同意你,這似乎是一個糟糕的設計。通用方法的目的就是GENERIC。只能是兩件事的「通用」不是非常通用的。如果你不用T來做其他事情,那麼你唯一可能使用的「標識符」 - 一個不受約束的T - 在體內就是一個System.Object。爲什麼不完全消除通用性,只是把「標識符」作爲一個對象? – 2009-06-04 20:18:19