C# - 何时使用 public int virtual,何时只使用 public int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12678833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# - when to use public int virtual, and when to just use public int
提问by Gravy
I am working through a tutorial 'Professional ASP.NET MVC 3' by J Galloway. In this tutorial, Jon shows us how to build the MVC music store.
我正在学习 J Galloway 的教程“Professional ASP.NET MVC 3”。在本教程中,Jon 向我们展示了如何构建 MVC 音乐商店。
I am at the part where we are creating CS classes to model the data using EF code first.
我正在创建 CS 类以首先使用 EF 代码对数据进行建模。
I allthe examples in the book, public virtual int property {get; set; }is used with no explanation. The term virtual is stuffed EVERYWHERE.
我在书中的所有例子,public virtual int property {get; set; }都是不加解释地使用的。虚拟一词无处不在。
Elsewhere on the web, I have not seen the term virtual used with any kind of concistency whatsoever.
在网络的其他地方,我还没有看到虚拟一词的使用有任何一致性。
Could anybody explain to me:
谁能给我解释一下:
- The purpose of the term 'virtual' in this particular context
- Is using 'virtual' necessary?
- Why do some people use 'virtual' and others do not?
- Why do some people only use 'virtual' when defining foreign keys?
- What is the best practice use of the term 'virtual'?
- 术语“虚拟”在此特定上下文中的用途
- 是否需要使用“虚拟”?
- 为什么有些人使用“虚拟”而有些人不使用?
- 为什么有些人在定义外键时只使用“虚拟”?
- 术语“虚拟”的最佳实践是什么?
Many thanks in advance
提前谢谢了
采纳答案by Andrew Hare
In order to truly understand the virtualkeyword you are going to want to read up on Polymorphism in general:
为了真正理解virtual关键字,您需要阅读一般的多态性:
Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means "many-shaped" and it has two distinct aspects:
At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.
Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.
多态性通常被称为继封装和继承之后的面向对象编程的第三支柱。多态性是一个希腊词,意思是“许多形状”,它有两个不同的方面:
在运行时,派生类的对象在方法参数和集合或数组等地方可能被视为基类的对象。发生这种情况时,对象的声明类型不再与其运行时类型相同。
基类可以定义和实现虚拟方法,派生类可以覆盖它们,这意味着它们提供自己的定义和实现。在运行时,当客户端代码调用该方法时,CLR 查找对象的运行时类型,并调用虚拟方法的覆盖。因此,在您的源代码中,您可以调用基类上的方法,并导致执行该方法的派生类版本。
Once you understand these concepts better you might be able to determine whether or not the method you are creating from the book needs to be virtualor not.
一旦你更好地理解了这些概念,你就可以确定你从书中创建的方法是否需要virtual。
回答by Anton Baksheiev
From docs
来自文档
The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.
virtual 关键字用于修改方法、属性、索引器或事件声明,并允许在派生类中覆盖它。
So if you need hide old functionality and add new one you can use virtual. The different applications need difference requrementce according on develop new modules and architecture..
因此,如果您需要隐藏旧功能并添加新功能,您可以使用虚拟。根据开发新模块和架构,不同的应用程序需要不同的要求。
see here http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx
在这里看到http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx
回答by Joshua Honig
See virtual (C# Reference). Adding the virtualkeyword allows the property to be overriden in derived classes, which is very likely when you're building the generalized base classes of an MVC app.
请参阅虚拟(C# 参考)。添加virtual关键字允许在派生类中覆盖该属性,这在您构建 MVC 应用程序的通用基类时很可能发生。
回答by iMortalitySX
Ok, so the term virtual, is basically meaning "overridable" (has base implementation), but not abstract (meaning no original implementation).
好的,所以术语虚拟基本上是指“可覆盖”(具有基本实现),但不是抽象的(意味着没有原始实现)。
The 'virutal' keyword is nessisary if you WANT someone to override your method or property, instead of 'hide' it.
如果您希望有人覆盖您的方法或属性,而不是“隐藏”它,则必须使用“virutal”关键字。
So this all applies to inheritance and polymorphism. A derived class can override a virtual method and make it's own implementation (or even call the base implementation in that method). By overriding, you can guarentee that your new method will be called polymorphically, instead of the base implementation.
所以这一切都适用于继承和多态。派生类可以覆盖虚拟方法并使其成为自己的实现(甚至调用该方法中的基实现)。通过覆盖,您可以保证您的新方法将被多态调用,而不是基本实现。
Inversly, using the 'new' keyword, you can 'hide' data members and methods. This will allow you to do your own implementation as well, but DOES NOT execute your new implementation polymorphically, it will use the base class implementation.
相反,使用“new”关键字,您可以“隐藏”数据成员和方法。这也将允许您执行自己的实现,但不会以多态方式执行您的新实现,它将使用基类实现。
Versioning with the Override and New Keywords (C# Programming Guide)
回答by Christopher Bales
Virtual ensures that inherited children classes override the base class by enforcing them to override the property. Without it the virtual keyword, a children object can't override the base functionality.
Virtual 通过强制子类覆盖属性来确保继承的子类覆盖基类。没有它 virtual 关键字,子对象不能覆盖基本功能。
回答by Mark Oreta
The reason that he uses the virtual keyword in his model is to enable Change Tracking proxies. This is something specific to Entity Framework (edit: also NHibernate, and possibly any other orm thanks @danludwig), and it allows EF to automatically manage the entities that you're mapping to the database.
他在模型中使用 virtual 关键字的原因是启用更改跟踪代理。这是特定于实体框架的东西(编辑:还有 NHibernate,可能还有其他任何形式,感谢@danludwig),它允许 EF 自动管理您映射到数据库的实体。
From MSDN:
来自 MSDN:
Each property that is mapped to a property of an entity type in the data model must have non-sealed (NotOverridable in Visual Basic), public, and virtual (Overridable in Visual Basic) get and set accessors.
映射到数据模型中实体类型的属性的每个属性都必须具有非密封(Visual Basic 中的 NotOverridable)、公共和虚拟(Visual Basic 中的 Overridable)get 和 set 访问器。
回答by danludwig
Could anybody explain to me:
谁能给我解释一下:
The purpose of the term 'virtual' in this particular context
Other users here answered this well with very good references.
Is using 'virtual' necessary?
It depends. Sometimes it is necessary, sometimes it is superfluous.
Why do some people use 'virtual' and others do not?
They use it when they need it, or when they think they might need it.
Why do some people only use 'virtual' when defining foreign keys?
When defining foreign keys for use by Object Relational Mapping tools like Entity Framework and NHibernate,
virtualis often necessary because these ORM tools dynamically create a new class that inherits from your class. These "dynamic proxy" classes override yourvirtualproperties to provide additional behavior needed to maintain foreign key consistency. In the case of NHibernate, all properties (not just foreign keys) must be markedvirtual. This is because NH dynamic proxies add custom behavior to decide which properties on your model to retrieve from the database, and which to avoid loading.What is the best practice use of the term 'virtual'?
Use it when you intend for a member (method or property) to be overridden in a more derived class. Do not use them in classes marked
sealed.
术语“虚拟”在此特定上下文中的用途
这里的其他用户很好地回答了这个问题,并提供了很好的参考。
是否需要使用“虚拟”?
这取决于。有时是必要的,有时是多余的。
为什么有些人使用“虚拟”而有些人不使用?
他们在需要或认为可能需要时使用它。
为什么有些人在定义外键时只使用“虚拟”?
当定义由对象关系映射工具(如实体框架和 NHibernate)使用的外键时,
virtual通常是必要的,因为这些 ORM 工具动态创建一个从您的类继承的新类。这些“动态代理”类会覆盖您的virtual属性,以提供维护外键一致性所需的额外行为。在 NHibernate 的情况下,所有属性(不仅仅是外键)都必须标记为virtual。这是因为 NH 动态代理添加了自定义行为来决定从数据库中检索模型上的哪些属性,以及避免加载哪些属性。术语“虚拟”的最佳实践是什么?
当您打算在更派生的类中覆盖成员(方法或属性)时使用它。不要在标记为 的类中使用它们
sealed。

