【发布时间】:2016-01-06 13:09:22
【问题描述】:
我有两个视图模型,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 我不知道该怎么做。
【问题讨论】:
-
为什么还需要这样的功能呢?为什么需要按类型访问属性?
-
因为否则我将不得不在控制器中复制代码
-
我的解决方案有用吗?
-
我无法在 ATM 上测试它。稍后会告诉你。
标签: c# asp.net-mvc generics helper