为了回答关于为什么虚拟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.
当预定的方法进行重写,那么程序员可以使延迟加载!