2013-04-11 40 views
0

我有這個接口:如何將類轉換爲在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(); 
    } 

我的概念是好的?這可能沒有動態?

回答

1

基礎上提供的代碼,我已經試過這編譯OK

public class Entities { 
    public class Customer { 
    } 
} 

public interface IRepository<T> { 
    T Get(int Id); 
} 

public class Customer<T> : IRepository<Entities.Customer> { 
    public Entities.Customer Get(int Id) { 
     var cliente = new Entities.Customer(); 
     return cliente; 
    } 
} 

public class foo { 

    public static IRepository<T> DoStuff<T>(int Id) { 
     var a = (IRepository<Entities.Customer>)Activator.CreateInstance(typeof(T)); 
     var b = (IRepository<T>)Activator.CreateInstance(typeof(T)); 

     return b; // an object 
    } 

} 

但是下面,我不知道是什麼T是指爲。當我運行,並調用

foo.DoStuff<Entities.Customer>(0); 

然後我得到的var a線運行時錯誤,因爲類Entities.Customer沒有實現接口IRepository<T>。如果我叫

foo.DoStuff<Customer<Entities.Customer>>(0); 

然後我得到的「變種b」線運行時錯誤,因爲類Customer<Entities.Customer>實現IRepository<Entities.Customer>,而不是IRepository<Customer<Entities.Customer>>

兩個例外是正確的,問題的,所以希望筆者能從這個答案中找出問題所在。

+0

也爲我編譯,但在運行時引發了一個「無法拋出異常」。 – 2013-04-11 18:57:41

+0

然後你可以發佈產生運行時錯誤的最小代碼嗎? – Stochastically 2013-04-11 18:59:36

+0

我從上面編輯的MVC調用DoStuff方法來顯示調用... – 2013-04-11 19:02:44

1

Activator.CreateInstance(typeof(T)); - 此爲您創建新的T實例,這是在你的榜樣Entities.Customer,但它看起來像你想創建的Customer<Entities.Customer>實例。

相關問題