新聞中心
摘要:C#是繼C++和Java語言后的又一面向?qū)ο蟮恼Z言,在語法結(jié)構(gòu),C#有很多地方和C++及Java相似,但是又不同于它們,其中一些關(guān)鍵特別需要引起我們的注意。

10年積累的成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站設(shè)計(jì)制作后付款的網(wǎng)站建設(shè)流程,更有榕江免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
C# virtual修飾符用于修改方法或?qū)傩缘穆暶?,在這種情況下,方法或?qū)傩员环Q作虛擬成員。虛擬成員的實(shí)現(xiàn)可由派生類中的重寫成員更改。
調(diào)用虛方法時(shí),將為重寫成員檢查該對(duì)象的運(yùn)行時(shí)類型。將調(diào)用大部分派生類中的該重寫成員,如果沒有派生類重寫該成員,則它可能是原始成員。
默認(rèn)情況下,方法是非虛擬的。不能重寫非虛方法。
不能將C# virtual修飾符與以下修飾符一起使用:
static abstract override
除了聲明和調(diào)用語法不同外,虛擬屬性的行為與抽象方法一樣。
◆在靜態(tài)屬性上使用C# virtual修飾符是錯(cuò)誤的。
◆通過包括使用 override 修飾符的屬性聲明,可在派生類中重寫虛擬繼承屬性。
上邊是微軟的官方說明,個(gè)人認(rèn)為,如果自己覺得這個(gè)方法通用性不強(qiáng)就用virtual去聲明這個(gè)方法,然后用戶可以根據(jù)自己不同的情況首先繼承它然后對(duì)它進(jìn)行重載。下面我們來看一下微軟給的例子:
示例
在該示例中,Dimensions 類包含 x 和 y 兩個(gè)坐標(biāo)和 Area() 虛方法。不同的形狀類,如 Circle、Cylinder 和 Sphere 繼承 Dimensions 類,并為每個(gè)圖形計(jì)算表面積。每個(gè)派生類都有各自的 Area() 重寫實(shí)現(xiàn)。根據(jù)與此方法關(guān)聯(lián)的對(duì)象,通過調(diào)用正確的 Area() 實(shí)現(xiàn),該程序?yàn)槊總€(gè)圖形計(jì)算并顯示正確的面積。
- // cs_virtual_keyword.cs
- // Virtual and override
- using System;
- class TestClass
- {
- public class Dimensions
- {
- public const double pi = Math.PI;
- protected double x, y;
- public Dimensions()
- {
- }
- public Dimensions (double x, double y)
- {
- this.x = x;
- this.y = y;
- }
- public virtual double Area()
- {
- return x*y;
- }
- }
- public class Circle: Dimensions
- {
- public Circle(double r): base(r, 0)
- {
- }
- public override double Area()
- {
- return pi * x * x;
- }
- }
- class Sphere: Dimensions
- {
- public Sphere(double r): base(r, 0)
- {
- }
- public override double Area()
- {
- return 4 * pi * x * x;
- }
- }
- class Cylinder: Dimensions
- {
- public Cylinder(double r, double h): base(r, h)
- {
- }
- public override double Area()
- {
- return 2*pi*x*x + 2*pi*x*y;
- }
- }
- public static void Main()
- {
- double r = 3.0, h = 5.0;
- Dimensions c = new Circle(r);
- Dimensions s = new Sphere(r);
- Dimensions l = new Cylinder(r, h);
- // Display results:
- Console.WriteLine("Area of Circle = {0:F2}", c.Area());
- Console.WriteLine("Area of Sphere = {0:F2}", s.Area());
- Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
- }
- }
本文題目:概述C#virtual修飾符
本文URL:http://m.5511xx.com/article/dpppchc.html


咨詢
建站咨詢
