请参阅 EntityFramework 文章和 Microsoft 的其他 ASP MVC 网络研讨会,例如;
1:http://www.asp.net/mvc/videos/5-minute-introduction-to-aspnet-mvc
他们使用 virtual 关键字在主模型和细节模型之间进行引用。
您能否解释一下 (1) 为什么他们使用 virtual 关键字以及 (2) 没有关键字会出现什么缺点?
问候
最佳答案
他们在您的第二个链接中指定了原因:
When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types during runtime and then overriding virtual properties to add the loading hook. To get lazy loading of related objects, you must declare navigation property getters as public, virtual (Overridable in Visual Basic), and not sealed (NotOverridable in Visual Basic). In the code above, the Category.Products and Product.Category navigation properties are virtual.
我能看到的唯一缺点是,与任何虚拟方法一样,它们的执行速度比非虚拟方法稍慢。您很可能永远无法检测到性能差异。
您会在第一次访问这些属性时看到延迟,因为延迟加载意味着第一次读取将导致数据库查询。
关于c# - 为什么在 C# 主从模型中使用 virtual 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7169980/