C # inheritance,

Source: Internet
Author: User

C # inheritance,

The concept of inheritance is also used in programming. class inheritance exists in object-oriented programming, such as C ++ and C. Inheritance (with encapsulation and polymorphism) is one of the three main features (also known as the "pillar") of object-oriented programming. Inherit new classes used to create reusable, extended, and modified behaviors defined in other classes. The inherited class of its members is called the "base class", and the class that inherits these members is called the "derived class ". A derived class can only have one direct base class. However, inheritance can be passed. If ClassB is derived from ClassC and ClassA is derived from ClassB, ClassC inherits the members declared in ClassB and ClassA.

V Preface

No matter in other communities or gardens, there are already countless posts or articles about the inheritance class. The topic about the inheritance class is also the old one. I wrote this blog post to deepen my understanding of inheritance. The so-called reading is just a hundred times self-explanatory. Some of the content in this blog post comes from my reading (C # advanced programming has been reading for the fifth time since I started to access C #, and each reading has a different effect .) Notes, and some understanding.

VC # inheritance 1. Implement inheritance

To declare a class derived from another class, you can use the following syntax:

    class LearningClass : BasicClass    {    }

If the class (or structure) is also derived from the interface, use commas to separate the base class and interface in the list:

  class LearningClass : BasicClass, BasicInterface, BasicInterface2    {    }

For the structure, the syntax is as follows:

    struct LearningStruct : BasicInterface, BasicInterface2    {    }
One restriction of the structure is that the structure does not support inheritance, but each structure is automatically derived from system and ValueType. In fact, we should be more careful: we cannot encode the structure of the type hierarchy, but the structure can implement the interface. In other words, the structure does not support implementation inheritance, but supports interface inheritance. In fact, the definition structure and class can be summarized:
  • The structure is always derived from system. ValueType, which can also be derived from any number of interfaces.
  • Classes are always derived from another class selected by the user. They can also be derived from any number of interfaces.

If no base class is specified in the class definition, the compiler assumes that system. Object is a base class. Therefore, the following two sections of code generate the same result:

  class LearningClass : Object    {    }    class LearningClass    {    }
2. virtual method:

Sometimes we inherit some methods of a base class and want to redefine this method. We can declare a base class function as virtual, and then rewrite this function in any derived class:

public class BasicClass    {        public virtual string GetMessage()        {            return "Basic class message";        }    }

The concept of virtual functions in C # is the same as that of standard 00P: virtual functions can be rewritten in a derived class. When you call a method, the appropriate method of the Class Object is called. In C #, functions are not virtual by default, but (except constructors) can be explicitly declared as virtual. This follows the C ++ approach, that is, from the performance perspective, unless explicitly specified, the function is not virtual. In Java, all functions are virtual. However, the syntax of C # is different from that of C ++, because C # requires explicit declaration using the override keyword when the function of the derived class overrides another function:

    class LearningClass : BasicClass    {        public override string GetMessage()        {            return "Learning class message";        }    }

The syntax of the override method avoids the potential running errors that are easy to occur in C ++: when the method signature of the derived class is slightly different from the base class version, this method cannot override the method of the base class: in C #, a compilation error occurs because the compiler considers the function as override but does not override the method of its base class.

Neither the member field nor the static function can be declared as virtual, because this concept only makes sense to the instance function members in the class.

3. Hiding method:

If the method with the same signature is declared in both the base class and the derived class, but this method is not declared as virtual and override, the derived class method will hide the base class method.

In most cases, the method should be rewritten, rather than hidden, because hiding the method will pose a risk of calling an error method for the instance of the given class. However, as shown in the following example, the C # syntax ensures that developers receive a warning of this potential error during compilation, so that the hidden string [if this is indeed the user's local secret, more secure. This is also the benefit of the version obtained by class library developers.

Public class LearningClass: BasicClass {public new string GetMessage () {return "Learning class message ";}}4. base class version of the called function:

C # has a special syntax used to call the base class version of a method from a derived class: base .(). For example, if a method in a derived class returns the return value of method 20% of the base class, you can use the following syntax:

    public class BasicClass    {        public virtual float GetPrice()        {            return 1.5f;        }    }    public class LearningClass : BasicClass    {        public float GetPrice()        {            return base.GetPrice() * 0.2f;        }    }

Ps: You can use the base. () syntax to call any method in the base class without calling it from the same method overload.

5. abstract classes and abstract functions:

C # declare classes and functions as abstract objects. Abstract classes cannot be instantiated, but abstract functions cannot be directly implemented. They must be rewritten in a non-image-like derived class. Obviously, abstract functions are also virtual (although virtual keywords are not required, a syntax error occurs if this keyword is provided. If a class contains an abstract function, the class is also abstract and must be declared as abstract:

    public abstract class BasicClass    {        public abstract float GetPrice();    }    public class LearningClass : BasicClass    {        public override float GetPrice()        {            return 0.2f;        }    }
6. sealing and sealing methods:

C # declare classes and methods as sealed. For classes, this indicates that the class cannot be inherited; for methods, this indicates that the method cannot be overwritten.

When marking a class or method as sealed, the most likely situation is: If you want to operate a class or method out of the scope of the library, class, or other classes written by yourself, rewrite some functions will cause code confusion. You can also mark a class or method as sealed for commercial reasons to prevent a third party from extending the class in violation of the authorization agreement. However, you should be careful when marking a class or member as sealed, because doing so severely limits its usage. Even if we believe that it cannot play a role on a member inheriting from a class or rewriting class, there may still be some unexpected situations at some time in the future, in this case, it is very useful .. NET-based class libraries use a large number of sealing classes, so that third-party developers who want to generate their own classes from these classes cannot access these classes. For example, string is a seal class.

Declaring a method as sealed can also achieve a similar goal, but this is rarely done.

7. modifier:

C # There are five access modifiers: public, private, protected, internal, and protected internal. The following table lists the application scopes:

Access Modifier Description
Public Public access. Not limited.
Private Private access. Only access by members of this category is allowed.
Protected Protect access. The instance cannot be accessed only by the class or subclass.
Internal Internal access. It is restricted to access within the project, and others cannot be accessed.
Protected internal Access is protected internally. Only access to this project or subclass is allowed.

C # The following table lists the modifiers and default modifiers of member types:

Member type Default Modifier Modifier
Enum Public None
Class Private Public, protected, internal, private,
Protected internal
Interface Public None
Struct Private Public, internal, private

Modifiers can be applied to type members and have different purposes:

Modifier Apply Description
New Function Member Hide inherited members with the same signature
Static All members The member does not act on a specific instance of the class.
Virtual Function member only A member can be rewritten by a derived class.
Abstract Function member only The Virtual Member defines the member signature but does not provide the instance code.
Override Function member only The member overrides the inherited virtual or abstract member.
Sealed Class, method, and attribute The class cannot inherit from the sealed class. For attributes and methods, a member overrides an inherited Virtual Member, but no member in any derived class can override this member. This modifier must be used with override
Extern Only static [DllImport] Methods Members are implemented externally in another language




Author:Please call my first brother
Exit: http://www.cnblogs.com/toutou/
About the author: focused on Microsoft platform project development. If you have any questions or suggestions, please kindly advise me!
Copyright Disclaimer: The copyright of this article is shared by the author and the blog site. You are welcome to reprint this article. However, you must keep this statement without the author's consent and provide the original article link clearly on the article page.
We hereby declare that all comments and private messages will be replied immediately. You are also welcome to correct the mistakes and make progress together. Or directly send a private message to me.
Support blogger: If you think the article is helpful to you, click the bottom right corner of the article[Recommended]. Your encouragement is the greatest motivation for the author to stick to originality and continuous writing!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.