Base class in Microsoft .NET inherits

zhaozj2021-02-17  52

Base class in Microsoft .NET inherits

Upgrade to Microsoft .NET

Paul D. Sheriffpdsa, Inc. December 2001 Abstract: This article introduces inheritance, explains how to inherit the base class, and introduce the implementation inheritance and interface inheritance in Microsoft .NET. the goal

Inheritance Overview Learn how to inherit the base class to understand the interface inheritance to understand the premise of the inheritance, you must completely understand the content of this article, you need to meet the following conditions:

Understand basic code understanding and its working principle, or reading CREANG CLASS IN .NET (English) A text directory can be used with Microsoft® Visual Basic® .NET Directory

Inherit Overview Inheritance Basis Construction Example Forms Creating Subcarpons Add Other Features MyBase Keyword Abstract Class Select The Inherit Type of Inheritance Type Visual Basic 6.0 Summary Summary Summary Summary Summary The main function of the object-oriented programming (OOP) language is " inherit". Inheritance refers to such capabilities: it can use all of the features of the existing class and expand these features without rewriting the original class. The Visual Basic programmers do not have this capability before Microsoft® Visual Basic® .NET is released. In Visual Basic .NET, you can inherit the class in the Microsoft .NET framework, you can also inherit the class you created yourself. In this article, we will learn how to use inheritance, and understand how inheritage greatly shorten the programming time. Simply Sample In many classes you created, you will find that you often need the same properties and methods as the properties and methods in the previously created classes. For example, if there is a base class named a Person class, the class contains the lastName and FirstName properties and the Print method, you will find that you also need these properties and methods for the Employe class. You may also need other properties such as EmployeID and Salary. If you inherit from the Person class (base class), you can add these properties to the new Employee class and can still access all properties in the Person class. Inheritance means that a class can define itself as all attributes and methods with a particular class, and then the ability to extend the definition of the base class by adding other properties and methods. Inheritance terminology allows us to define several terms before deeply studying this topic. By inheriting new classes are called "subclasses", the inherited class is called "base class", "parent class" or "super class". In some OOP languages, a subclass can inherit multiple base classes. That is, if there is a Person class and a CAR class, the Driver class can inherit all attributes and methods of these two classes. In .NET, only single inherit is allowed, so each subclass can only have a base class. .NET supports three types of inheritance: achieve inheritance, interface inheritance and visual inheritance. Implementation inheritance refers to the ability to use the properties and methods of the base class without additional coding; interface inheritance refers to the name of only the properties and methods, but the subclass must provide the ability to implement; visual inheritance refers to the fingers (class) Use the appearance of the base (class) and the ability to implement the code. In .NET, a class can inherit a base class, and this base class can inherit from another class. Moreover, you can use one or more interfaces in a class. The reasons for use inheritance can avoid repeating the same code, so it is useful. If there are two separate classes, each class must implement the firstname and lastname properties, the repetition code may occur. If you want to change an implementation of an attribute, you need to find all classes that have implemented these properties for changes. This is not only a lot of time, but also increases the risk of errors in different classes. When considering the inheritance, it is necessary to pay attention to it, that is, the relationship between the two classes should be "belonging to". For example, EMPLOYEE is a person, and Manager is also a person, so these two classes can inherit the Person class. But the Leg class cannot inherit the Person class, because the leg is not a person. When overridden from the inheritance function from the base class, you may find that the general method prepared in the base class onlys the partial functions required for the inheritance class. To perform the required features, you can overwrite the basic class in the new class without having to create a new method using the new name.

When you override, you can choose a method of fully overwriting the base class, or you can write code in the inheritance class to perform some operations, and then call the base class. When override, be sure to use the same contract as the original method (parameters, and return types). You can also select the method of calling the base class first, and then write other code after performing the basic class. Inheritance base type inheritors allows you to use all of the properties and methods of another class in a class. You can use the keyword inherits to get the base class's feature without having to copy and paste the code from a class class and paste it into another class. Implementation Inherit This article will create a new class Linedelim that will inherit all features of the Line class created in the CREATING CLASSES IN .NET (English). Thereafter, this article will expand the Line class by adding two other properties and one way. The first attribute to be added is Delimiter, use it to get a separator character and set it to the class. This separator will be used to replace all spaces in the row with a separator character. The second attribute to be added is OriginalLine, which will be used to retain the original line of the text before inserting a new separator to the text row. The new method to be created is ReplaceAll (), which will be used to replace all spaces in the text line to a delimiter character. Then we will learn how to override the getWord method so that this separator (not space) is separated by the text line and searches the first word. Building an example form 4 The sample form shown in Figure 1 will be used to test inheritance classes to be created. Figure 1: Sample form for testing inheritance To create the form shown in Figure 1, click Project, and then click Add Windows Form. Name the form to frmlinetest.vb and click OK. The corresponding control is then created on the form and set the properties, as shown in Table 1. Table 1: Form for testing inheritance

Control property values ​​LabelNameLabel1 TextLine of TextTextBoxNametxtLine TextThe rain in Spain stays mainly in the plainTextBoxNametxtDelim Text, GroupBoxNamefraWord TextGet First WordCommandButtonNamebtnFirst TextGet WordTextBoxNametxtFirstWord Text ReadOnlyTrueCommandButtonNamebtnReplace TextReplaceTextBoxNametxtReplace Text ReadOnlyTrue building will be built next to the Line class inherits the Line class.

Click Project from the menu, and then click Add Class. Type the code as shown below. Public Class Line

Private MSTRLINE AS STRING

Property line () AS STRING

Get

Return MSTRLINE

END GET

Set (byval value as string)

MSTRLINE = Value

End set

End Property

Readonly Property Length () AS INTEGER

Get

Return Mstrline.Length

END GET

End Property

Public function getWord () AS String

Dim as string () AS STRING

askRWORDS = MSTRLINE.SPLIT ("" .tochararray ()) Return AstrWords (0)

END FUNCTION

END CLASS

Creating subclasses Since the forms and base classes have been created, they can now start inheritance.

Click Project, and then click Add Class. Name this class Linedelim.vb and click OK. When you add a new class, modify the code created by Visual Basic .NET to make it similar to the sample code below. Public Class Linedelim

Inherits Line

End Class Because adding Inherits Line statements, you can use all properties and methods of the Line class in this new class. Try a try

Open the FRMLINETEST.vb form. Double-click the GET Word button. Add the following code to this button: protected sub btnfirst_click (Byval Sender as Object, _

Byval e as system.eventargs) Handles btnfirst.click

DIM Oline as Linedelim = New Linedelim ()

Oline.Line = txtline.text

TXTFIRSTWORD.TEXT = Oline.GetWord ()

End Sub Run the project and click the Get Word button on the form. You will see the "The" word appears in the read-only text box next to the button. Inherits statements are very powerful, just use this statement, you can use all properties and methods of the LINE class in the Linedelim class. Although this new category has not performed any new operations, it demonstrates all the code inherited from the Line class. Add additional features Now you can use other properties and methods to extends the Linedelim class. To add two new properties to the LINEDELIM class, perform the following steps.

After adding the inherits statement added by the previous part, add two private variables as shown below. Private mstrdelim as string = ""

Private MstructIginal AS String Type the following code to add the appropriate Property statement for the two private variables. You can place the following code behind the two row code entered above (next to these two lines). Public property Delimiter () AS String

Get

Return MSTRDELIM

END GET

Set (byval value as string)

MSTRDELIM = VALUE

End set

End Property

Public Readonly Property Originalline () AS String

Get

Return Mstructiginal

END GET

End Property Now you can use the Delimiter property to set and get the value of the private variable MStrDelim. If you don't want others to change these properties, you can set the properties to read-only. To do this, no longer use the set statement and add the readOnly property in the Property statement. For example, see the originaLine property declaration displayed in the above code. Next, you need to create a method called ReplaceAll that replaces all spaces in the text line to the separator character passed to the DELIMITER attribute. Public Function ReplaceAll () AS StringmstructiGinal = MyBase.Line

Return mybase.Line.Replace ("", mstrdelim.tochar ())

The End Function ReplaceAll method retrieves the original text line through the LINE method of the base class. The MyBase.Line syntax is used when retrieving properties from the base class. The ReplaceAll function puts the value of mybase.line properties into the private variable you just created for this class MStructigiGinal. The Replace method of the String data type replaces all instances of string characters to new divider characters MSTRDELIM set in the Delimiter property. MyBase keywords can use myBase keywords from any subclass to invoke any properties or methods in the base class. Even if the method of the base class is overwritten in the subclass, you can use this keyword to call it. For example, if there is a ReplaceAll method in the base class, the method has been overwritten in the subclass, and you can call the REPLACEALL method for the base class from the ReplaceAll method of the subclass. Try a try

Open the FRMLINETEST.vb form. Double-click Replace to call up the click event process. Write the following code in the click event of the BTNREplace button: protected sub btnreplace_click (_

Byval sender as object, _

Byval e as system.eventargs) Handles btnreplace.click

DIM Oline as Linedelim = New Linedelim ()

Oline.delimiter = txtdelim.text

Oline.Line = txtline.text

TXTREPLACE.TEXT = Oline.ReplaceAll ()

End Sub This code sets the DELIMITER attribute to the value entered in the TXTDELIMITER text box of the sample form. You can then call the ReplaceAll method, change all spaces in the text line to the new separator character. Press F5 to run the project. Click Replace. You will see that there is a comma between each word in the sentence next to this button. Once the overlay method adds the Delimiter property, you may want to change the getWord method in the Linedelim class to use the appropriate separator to replace a single space used by the Line class. Because you don't have to change the base class, you need to override the functionality of the getWord method in the Linedelim class. Before you create a new getWord method in the Linedelim class, you need to add a keyword in the getWord method declaration of the Line class.

In the Solution Explorer window, open the LINE.vb class's code window. Find a declaration of getWord method (declaration does not include parameters), as shown below: Public overloads function getword () AS String Adds keyword overridable in a function declaration, as shown below (without this keyword, it will not overwrite this method). Public overridable overloads function getword () AS String Opens the Linedelim.vb class and add a new getWord method using the following code. Public overloads overrides function getword () AS stringdim astrwords () AS STRING

askRWORDS = MyBase.Line.Split (mstrdelim.tochararray ())

Return astrwords (0)

End function If you want to change the functionality of the method in the base class, it is necessary to add an Overrides keyword in the function declaration. The getWord method in the Linedelim class can now use the value of the DELIMITER attribute to separate the words in the sentence. If only one getWord method is only overwritable, the code can only view this version of the way, and the other version of the getWord method cannot be called. To display all methods, you must override each method, just like you do in the Linedelim class. Try a try

Press F5 to run the project. Enter a comma between each word in the sentence and enter a comma in the Delimiter text box. Click Get Word. The first word in the sentence will appear in the text box next to this button. Abstract Class In the example of this article, we learned how to create a Person object because we want to handle ordinary people. But you may find that if you don't add some specific behavior and / or data, you cannot perform any action using the Person class. So you can turn the Person class to an abstract class, and the abstract class only defines the general properties and methods that will be created by the subclass. Define the Person class as an abstract class that can only be inherited instead of the object actually created at runtime. Each class (such as the EMPLOYEE class) inherited from this class will use a specific function to create all the corresponding properties and methods. For example, the Employee class will create the actual Print method, and the Person class only defines the required print method; the Person class is not associated with the Print method. There are a variety of reasons for using abstract classes. The abstraction class is very useful for all the interfaces that the forced sub-designers implement applications. You can add new methods to subclasses without damaging client applications, which is unable to use the interface; you can provide many default implementation methods in the base class, thereby reducing subclasses need to complete the workload. When the interface inherits creates an abstract class, use the keyword interface instead of the Class. Named the interface and define all properties and methods that require subclass implementations. This is because the properties and methods that can be implemented in the base class, which only contains general data without including methods. It is only a contract that you created, which specifies that all subclasses that use this interface must follow certain rules.

Now, add a new class in the created project. From the Visual Studio menu, click Project, and then click Add Class. Add the following code to the class: Interface PersonProperty FirstName () AS String

Property lastname () AS STRING

SUB Print ()

SUB Talk ()

End Interface You will find that the method you define the property and sub-process is the same as that of you usually define these properties and procedures. The only difference is that you didn't write any code for them. Take a look at how to use this interface in class definitions. Add the following code to the class file created in the previous step: public class Employee

Implements Person

Private mstrfirstname as string

Private mstrlastname as string

Property firstname () AS STRING _

IMPLEMENTS PERSON.FIRSTNAME

Get

Return mstrfirstname

END GET

Set

mstrfirstname = value

End set

End Property

Property lastname () AS STRING _

Implements Person.lastname

Get

Return MSTRLASTNAME

END GET

Set

MSTRLASTNAME = VALUE

End set

End Property

SUB Print () Implements Person.print

'Add some code here

End Sub

SUB Talk () Implements Person.talk

'Add some code here

End Sub

The first line of End Class after the Employee class definition is Implements Person. This keyword indicates that you are following the contract defined in the Person interface. Now you can define all properties and methods in the contract. Behind each Property statement, you must include the imports keyword, and you must specify the name of the interface and the name of the method / attribute you are using (there is a point between the two names [.]). Visual Basic .NET will track each interface and you cannot compile the application before all interfaces are created. If you want to run the code, you need to create a corresponding child process because these subsections are retained empty in the example above. Once you have created all the child, you can create and use any other objects as you usually create and use the new Employee object. Choosing the type of inheritance to use is sometimes difficult to determine whether to implement inheritance or use interface inheritance, in many cases, it may be used in both inheritance, but only a small part. For example, you may need to add a method definition that must be submitted by subcategories in the Line class, which can be implemented using the Mustoverride keyword in the process definition. Public Mustoverride Sub init () After adding this definition to the class, its effect is similar to an interface. In the subclass, the init method must be defined and the method must use the Overrides keyword. Here's how to define an init method: public overrides subinit ()

MSTRDELIM = ""

MStrline = "Test line"

Also, remember to use the Overrides keyword. This keyword is used to notify the compiler that this method will overwrite the Init method in the parent class. note:

Design Guide provides a design guide in the online help of the Microsoft .NET Framework, you can help you decide the inheritance type to use.

Block inheritance In some cases, you may not want other classes to inherit your class. If so, you can use keyword notinheritable to block the inheritance of the class. Public Class Notinheritable Employee

'Definition

End Class Visual Basic 6.0 has used Visual Basic .NET, you can inherit all classes included in the .NET framework. You can create your own class so that these classes inherit the existing classes; and add or delete the function by simply changed the code. Summary This article describes how to inherit the base class, how to add other properties to the base class, and how to use the Overrides keyword to replace the functions defined in the base class. It also introduces the method in which the method in the base class is called using the MyBase keyword, thereby expanding the function of the base class. Although inheritance is not applicable to all applications, if the use is correct, inheritance will become a very powerful tool. About the author Paul D. Sheriff is the owner of PDSA, Inc.. The company is located in Southern California, is a custom software development and consulting firm. Paul is the MSDN regional director of South California, with a book of "Paul Sheriff Teaches Visual Basic", who made more than 70 sets of video textbooks developed about Visual Basic, SQL Server, .Net and Web for Keystone Learning Systems, recently Cooperation with Ken Getz published a book about SAMS, the title is "ASP.NET JUMPSTART". For more information, please visit the Web site of PDSA, Inc. www.pdsa.com. About Informant Communications Group Informant Communications Group, Inc. is a multimedia company specializing in the information technology industry. It was established in 1990, specializing in software development publications, meetings, catalog issues, and Web sites. ICG has offices in the United States and the United Kingdom. It has now become a highly reputable media and marketing content integrator, and meets the growing demand for IT staff with high quality technical information. © Informant Communications Group and Microsoft Corporation Copyright © INFORMANT COMMUNICATION Technical Editor: PDSA, Inc.

转载请注明原文地址:https://www.9cbs.com/read-29536.html

New Post(0)