爲了回答關於爲什麼虛擬ICollection的使延遲加載在EF的問題,我們需要在該虛擬關鍵字的定義和含義C#。從MSDN:
The virtual keyword is used to modify a method, property, indexer or event declaration,
and allow it to be overridden in a derived class. For example, this method can be
overridden by any class that inherits it.
距離Object Oriented Programming概念的繼承機制的一部分。
它往往是的情況下,一個子類需要另一個(擴展)的功能的基類。在這種情況下,虛擬關鍵字允許程序員倍率(基類的用於該當前實施的默認實現如果需要的話,但所有其他預定義的方法/屬性/等仍從基類取!
一個簡單的例子是:
// base digit class
public class Digit
{
public int N { get; set; }
// default output
public virtual string Print()
{
return string.Format("I am base digit: {0}", this.N);
}
}
public class One : Digit
{
public One()
{
this.N = 1;
}
// i want my own output
public override string Print()
{
return string.Format("{0}", this.N);
}
}
public class Two : Digit
{
public Two()
{
this.N = 2;
}
// i will use the default output!
}
當創建兩個對象和打印叫做:
var one = new One();
var two = new Two();
System.Console.WriteLine(one.Print());
System.Console.WriteLine(two.Print());
的輸出是:
1
I am base digit: 2
懶評價在EF中不是來自虛擬關鍵字直接,但是從覆蓋可能性關鍵字,可以(再次從MSDN上延遲加載):
When using POCO entity types, lazy loading is achieved by creating
instances of derived proxy types and then overriding virtual
properties to add the loading hook.
當預定的方法進行重寫,那麼程序員可以使延遲加載!