2 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
我想你可能對(duì)這個(gè)有一個(gè)小小的誤解IEnumerable
。它只是說該類支持迭代。它不會(huì)直接影響數(shù)據(jù)的獲取方式。
此外,IQueryable
實(shí)現(xiàn)IEnumerable
,因此所有IQueryable
實(shí)例也是IEnumerable
。這是有道理的,因?yàn)槟梢缘Y(jié)果。
在您的示例中,缺少這意味著IQueryable
“從數(shù)據(jù)庫檢索所有行,然后在 C# 中進(jìn)行過濾”。

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
LINQ 中有 2 個(gè)不同的擴(kuò)展 -?IEnumerable和IQueryable。
當(dāng)您編寫EntityRepository<Attachment>().Entities
.Where(at => at.EntityType == EntityType.EmailTemplate)
編譯器時(shí),它會(huì)檢查類型Entities
,并聲明“更具體”,IQueryable
編譯器會(huì)選擇Queryable.Where()
方法,并且表達(dá)式由IQueryProvider轉(zhuǎn)換為 SQL。當(dāng)您編寫時(shí),.ToDictionary(at => at.Extension, at => at)
編譯器找不到Queryable.ToDictionary()
,因此它會(huì)回退到Enumerable.ToDictionary()
內(nèi)存中過濾項(xiàng)目。
C# 語言規(guī)范中定義了擴(kuò)展方法調(diào)用規(guī)則:
候選方法集被簡(jiǎn)化為僅包含來自最派生類型的
C.F
方法:對(duì)于集合中的每個(gè)方法,其中C
是聲明該方法的類型F
,所有在 的基類型中聲明的方法都C
將從集合中刪除。此外,如果C
是 以外的類類型object
,則接口類型中聲明的所有方法都將從集合中刪除。(后一條規(guī)則僅在方法組是對(duì)具有除 object 之外的有效基類和非空有效接口集的類型參數(shù)進(jìn)行成員查找的結(jié)果時(shí)才有效。)
?public interface IInterfaceA { }
? ? public interface IInterfaceB : IInterfaceA { }
? ? public static class MyExtensions {
? ? ? ? public static void Print(this IInterfaceA a) => Console.WriteLine("A");
? ? ? ? public static void Print(this IInterfaceB b) => Console.WriteLine("B");
? ? }
? ? public class AB: IInterfaceA, IInterfaceB { }
? ? public class BA: IInterfaceB, IInterfaceA { }
? ? public partial class Program
? ? {
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? new AB().Print(); // B
? ? ? ? ? ? new BA().Print(); // B
? ? ? ? }
? ? }
- 2 回答
- 0 關(guān)注
- 144 瀏覽
添加回答
舉報(bào)