2012-03-06 72 views
4

我有以下擴展方法:擴展方法沒有發現(未裝配參考問題)

public static EntitySet<T> ToEntitySetFromInterface<T, U>(this IList<U> source) 
    where T : class, U 
{ 
    var es = new EntitySet<T>(); 
    IEnumerator<U> ie = source.GetEnumerator(); 
    while (ie.MoveNext()) 
    { 
     es.Add((T)ie.Current); 
    } 
    return es; 
} 

和Im嘗試如下使用它:

List<IItemMovement> p = new List<IItemMovement>(); 
    EntitySet<ItemMovement> ims = p.ToEntitySetFromInterface<ItemMovement, IItemMovement>(); 

其中ItemMovement實現IItemMovement。編譯器會抱怨:

「System.Collections.Generic.List」不包含一個 定義爲「ToEntitySetFromInterface」和沒有擴展方法 「ToEntitySetFromInterface」接受 類型的第一參數「System.Collections.Generic 。列表'可以找到( 你缺少一個使用指令或程序集參考嗎?)

不,我不缺少一個參考。如果我只是輸入包含它彈出的方法的靜態類的名稱,那麼擴展方法也是如此。 Thnx

+0

im not sure List list = new List ();會編譯? – AaronHS 2012-03-06 11:30:18

+1

否則這個代碼適用於我(帶有嘲弄的ItemMovement和IItemMovement – AaronHS 2012-03-06 11:32:24

+2

我相信這個問題與intellisense無關,如果你不能編譯它,那麼它幾乎不會是intellisense的錯誤 – demoncodemonkey 2012-03-06 11:45:48

回答

2

此代碼適用於我,並且它是您的代碼的直接副本,減去ItemMovement及其接口,因此該部分可能有問題?

public class TestClient 
{ 
    public static void Main(string[] args) 
    { 
     var p = new List<IItem>(); 
     p.Add(new Item { Name = "Aaron" }); 
     p.Add(new Item { Name = "Jeremy" }); 

     var ims = p.ToEntitySetFromInterface<Item, IItem>(); 

     foreach (var itm in ims) 
     { 
      Console.WriteLine(itm); 
     } 

     Console.ReadKey(true); 
    } 
} 

public class Item : IItem 
{ 
    public string Name { get; set; } 
    public override string ToString() 
    { 
     return Name; 
    } 
} 

public interface IItem 
{ 
} 

public static class ExtMethod 
{ 
    public static EntitySet<T> ToEntitySetFromInterface<T, U>(this IList<U> source) where T : class, U 
    { 
     var es = new EntitySet<T>(); 
     IEnumerator<U> ie = source.GetEnumerator(); 
     while (ie.MoveNext()) 
     { 
      es.Add((T)ie.Current); 
     } 
     return es; 
    } 
} 
+0

好吧我覺得真的這不是一個彙編ref問題,但它是一個使用問題,我複製了你的代碼並且它工作了,但是當我把它複製到與上面的代碼相同的類文件時,我沒有想到我已經打折了命名空間問題,通過測試我是否可以調用擴展方法類LinqExtensions,實際上我可以。因此,不確定如何在不使用完全限定名稱空間的情況下調用該類,但如果使用未正確聲明,則無法使用擴展方法? Thnx。 – rism 2012-03-06 21:34:27

1

編譯器錯誤的這一部分是鍵:「沒有擴展方法‘ToEntitySetFromInterface’接受類型‘System.Collections.Generic.List’的第一個參數」。

您的ToEntitySetFromInterface<T,U>擴展方法定義爲接受IList<U>,但您試圖用List<T>而不是IList<T>來調用它。由於類型不匹配,compliler沒有找到您的擴展方法。

+0

你好,我不明白你的意思是列表?我打電話給ToEntitySe tFromInterface (this IList source),所以IList類型由IItemMovement的U類型定義,即ILIst 。因爲(這個IList 源)決定了擴展方法可以應用於哪種類型,在這種情況下是IList 和p = IList ,我不太關注你所說的。注意上面我有:列表但即使改變到IList 我仍然得到相同的問題/錯誤。 – rism 2012-03-06 21:04:43

+0

@rism,我錯了。我很抱歉。 – 2012-03-07 10:54:07