[英]MVC ASP.net Creating a generic helper
我有兩個視圖模型, PublishedSong
和RadioStation
,我希望它們具有IncrementViews(int id)
函數。
與其將功能復制並粘貼到兩個控制器中,我不希望創建一個通用的幫助器類。
幫手:
public class CustomDBHelper<T>
{
public static IEnumerable<T> GetElements(ApplicationDbContext db, T type)
{
if (type.Equals(typeof(SongsController)))
return (IEnumerable<T>)db.PublishedSongs;
else if (type.Equals(typeof(RadioStationsController)))
return (IEnumerable<T>)db.RadioStations;
else
throw new Exception("Controller not found, DBHelper");
}
}
控制器:
public class MusicBaseController : Controller
{
public JsonResult IncrementViews(int id)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
db.PublishedSongs.Single(x => x.Id == id);
var element = CustomDBHelper<T>.GetElements(db, this.GetType()).Single(x => x.Id == id);
element.UniquePlayCounts++;
db.SaveChanges();
return Json(new { UniquePlayCounts = element.UniquePlayCounts }, JsonRequestBehavior.AllowGet);
}
}
}
我在這行上遇到麻煩: var element = CustomDBHelper<T>.GetElements(db, this.GetType()).Single(x => x.Id == id);
<T>
無效。 我是通用類的新手,我認為它需要一個類,但是由於該類可能是PublishedSong
或RadioStation
所以我不知道該怎么做。
以下實現將為您工作:
public class CustomDBHelper
{
public static IEnumerable GetElements(ApplicationDbContext db, Type type)
{
if (type.Equals(typeof(SongsController)))
{
return db.PublishedSongs;
}
else if (type.Equals(typeof(RadioStationsController)))
{
return db.RadioStations;
}
else
{
throw new Exception("Controller not found, DBHelper");
}
}
}
並且您將需要將此函數的結果強制轉換為所需的類型。
附帶說明一下,類型泛型也可以用作類型泛型。 由於您將類型作為參數傳遞,因此沒有必要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.