intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Sealed Classes

Chia sẻ: Nghia Tuan | Ngày: | Loại File: PDF | Số trang:1

67
lượt xem
4
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Sealed Sử dụng các lớp kế thừa không phải luôn luôn dễ dàng và đòi hỏi phải suy nghĩ. Nếu bạn tạo một giao diện hoặc lớp một trừu tượng, bạn đang cố ý viết cái gì đó sẽ được thừa hưởng từ trong tương lai. Điều rắc rối là dự đoán tương lai là một doanh nghiệp khó khăn.

Chủ đề:
Lưu

Nội dung Text: Sealed Classes

  1. Sealed Classes Using inheritance is not always easy and requires forethought. If you create an interface or an abstract class, you are knowingly writing something that will be inherited from in the future. The trouble is that predicting the future is a difficult business. It takes skill, effort, and knowledge of the problem you are trying to solve to craft a flexible, easy-to- use hierarchy of interfaces, abstract classes, and classes. To put it another way, unless you consciously design a class with the intention of using it as a base class, it's extremely unlikely that it will function very well as a base class. Fortunately, C# allows you to use the sealed keyword to prevent a class from being used as a base class if you decide that it should not be. For example: sealed class LiteralToken : DefaultTokenImpl, IToken { ... } If any class attempts to use LiteralToken as a base class, a compile-time error will be generated. A sealed class cannot declare any virtual methods. The sole purpose of the virtual keyword is to declare that this is the first implementation of a method that you intend to override in a derived class, but a sealed class cannot be derived from. NOTE A struct is implicitly sealed. You can never derive from a struct. Sealed Methods You can also use the sealed keyword to declare that an individual method is sealed. This means that a derived class cannot then override the sealed method. You can only seal an override method (you declare the method as sealed override).You can think of the interface, virtual, override, and sealed keywords as follows: • An interface introduces the name of a method. • A virtual method is the first implementation of a method. • An override method is another implementation of a method. • A sealed method is the last implementation of a method.
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2