为了回答虚拟 ICollection为什么在 EF 中启用延迟加载的问题,我们需要 C# 中virtual关键字的定义和含义。来自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.
它是面向对象编程概念的继承机制的一部分。
通常情况下,子类需要另一个(扩展)功能作为基类。在这种情况下,virtual关键字允许程序员重写(如果需要,此当前实现的基类的默认实现,但所有其他预定义的方法/属性/等仍然取自基类!
一个简单的例子是:
// 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!
}
当创建两个对象并调用Print时:
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 中的延迟评估不是来自virtual关键字 direct,而是来自关键字启用的覆盖可能性(再次来自MSDN on Lazy Loading):
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.
当预定义的方法被覆盖时,程序员可以启用延迟加载!