我有這個接口:如何將類轉換爲在c#中使用泛型的接口?
public interface IRepository<T>
{
List<T> List();
T Get(int Id);
bool Add(T entity);
bool Update(T entity);
}
而且我有這個類:
public class Customer<T> : IRepository<Entities.Customer>
{
public Entities.Customer Get(int Id)
{
var c = new Entities.Customer();
return c;
}
//continue...
}
我如何可以投一個泛型類的通用接口,像這樣:
//Other method
public IRepositorio<T> DoStuff<T>(int Id)
{
var a = (IRepository<Entities.Customer>)Activator.CreateInstance(typeof(T)); // ok
var b = (IRepository<T>)Activator.CreateInstance(typeof(T)); // Exception: unable to cast
return object; // an object
}
我打電話給這臺MCV控制器:
public ActionResult Home()
{
var repo = new Repository();
repo.DoStuff<Customer<Entities.Custormer>>(10);
return View();
}
我的概念是好的?這可能沒有動態?
也爲我編譯,但在運行時引發了一個「無法拋出異常」。 – 2013-04-11 18:57:41
然後你可以發佈產生運行時錯誤的最小代碼嗎? – Stochastically 2013-04-11 18:59:36
我從上面編輯的MVC調用DoStuff方法來顯示調用... – 2013-04-11 19:02:44