Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C# 抽象


抽象类和方法

数据抽象是指隐藏某些细节,只向用户展示必要信息的过程。
抽象可以通过抽象类接口实现(您将在下一章中了解更多相关内容)。

关键字abstract用于类和方法

  • 抽象类:是一个受限的类,不能用于创建对象(要访问它,必须从另一个类继承)。

  • 抽象方法:只能在抽象类中使用,并且没有方法体。方法体由派生类(从其继承的类)提供。

抽象类可以包含抽象方法和普通方法。

abstract class Animal 
{
  public abstract void animalSound();
  public void sleep() 
  {
    Console.WriteLine("Zzz");
  }
}

从上面的示例中可以看出,无法创建 Animal 类的对象。

Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the abstract class or interface 'Animal')

要访问抽象类,必须从另一个类继承。让我们将我们在多态一章中使用的 Animal 类转换为抽象类。

请记住,在继承一章中,我们使用 :符号来继承一个类,并使用override关键字来重写基类方法。

示例

// Abstract class
abstract class Animal
{
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep()
  {
    Console.WriteLine("Zzz");
  }
}

// Derived class (inherit from Animal)
class Pig : Animal
{
  public override void animalSound()
  {
    // The body of animalSound() is provided here
    Console.WriteLine("The pig says: wee wee");
  }
}

class Program
{
  static void Main(string[] args)
  {
    Pig myPig = new Pig(); // Create a Pig object
    myPig.animalSound();  // Call the abstract method
    myPig.sleep();  // Call the regular method
  }
}

尝试一下 »

为什么要使用抽象类和方法以及何时使用?

为了实现安全性 - 隐藏某些细节,只显示对象的必要信息。

注意:抽象也可以通过接口实现,您将在下一章中了解更多相关内容。

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.