2013-09-26 38 views
1

我有以下代碼C#泛型類和方法不表現爲預期

public class BaseDataRepository<T> : IDataRepository, IDisposable where T:class 
    { 
     public IQueryable<T> GetItems<T>() where T : class 
     { 
      return _context.Set<T>(); 
     } 
    } 
} 

採用以下方式

using (var repository = new BaseDataRepository<DbInterestGroupCategory>()) 
{ 
    Assert.IsTrue(repository.GetItems().Count() == 3); 
} 

但我得到以下信息

類型參數方法'...'不能從使用中推斷出來。 嘗試明確指定類型參數。

我原以爲這個方法會自動從泛型類中推出它的T參數。我究竟做錯了什麼?

+0

你應該會看到一個警告編譯大約具有相同的名稱作爲外部類典型的方法類型參數e參數。 – juharr

回答

0

您正在重新聲明方法級別的泛型參數(它已在類級別上定義),因此您現在在泛型類中具有(獨立)泛型方法。即你可以寫這樣的代碼:

//DbInterestGroupCategory is the class-level T 
var repository = new BaseDataRepository<DbInterestGroupCategory>(); 
//string is the method level T 
repository.GetItems<string>(); 

你做了什麼本質上是類似於

public class MyClass 
{ 
    public string Name {get; set;} 

    public string Method() 
    { 
    string Name; // hides the class level property 
    .... 
    } 
} 

你需要的是相對於類一般不是一種方法,因爲它不引入任何通用的參數,它僅僅使用在類中已定義的那些,所以正確的語法是:

public IQueryable<T> GetItems() 
{ 
    return _context.Set<T>(); 
} 
+0

謝謝,很好的解釋和解決方案 – NZJames

9

取下方法<T>你已經宣佈它在課堂上

public class BaseDataRepository<T> : IDataRepository, IDisposable where T:class 
{ 
    public IQueryable<T> GetItems() 
    { 
     return _context.Set<T>(); 
    } 
} 

T的方法是通過參數推斷出這樣的:

public void DoSomething<T>(T argument) // infer T from argument 
{ 
} 

// so you can call 

DoSomething(new object()); // T is object 
+0

毆打7秒。打的好! – CodingIntrigue

1

通過聲明的方法GetItems<T>,你正在創建一個新的「T」模板變量不一樣。去掉它。