[Csharp]5 Inheritance and polymorphism

Source: Internet
Author: User
Tags class manager

Sealed keywords

If we mark the class as sealed, the compiler will not allow us to derive from this type. (C # Structures are always implicitly sealed.) Therefore, we can never inherit a struct from a struct, inheriting a struct from a class, or inheriting a class from a struct. Structs can only be used to model separate, user-defined data types. If you want to be a is-a relationship, you must use a class. )


Controlling the creation of base classes using the base keyword


Protected keywords

Derived types no longer need to use public methods or properties to access data indirectly. Of course, the downside is that if a derived type has direct access to its parent's internal data, it is possible to occasionally bypass the existing business rules set within the public attribute. When a protected member is defined, a trust level between the parent class and the subclass is created, and the compiler does not catch any exceptions that violate the type business rules.


Include/delegate programming

Class Benefitpackage

{

Public double computepaydeduction ()

{return 125.0; }

}

Partial class Employee

{

Protected benefitpackage empbenefits=new benefitpackage ();

Public double Getbenefitcost ()

{return empbenefits.computepaydeduction (); }

Public Benefitpackage Benefits

{get {return empbenefits; }

set {empbenefits=value; }

}

.......

}


Nested types

public class Outerclass

{

Public nested types can be used by anyone

public class Publicinnerclass {}

Private nested types can only be used by members of the containing class

public class Privateinnerclass {}

}

Characteristics of nested types:

A nested type gives you full control over the access level of an internal type, which can be declared private (recall that non-nested classes cannot be declared with the Private keyword).

Because a nested type is a member of a containing class, it can access the private members of the containing class.

In general, nested types are used only as helper methods for external classes, not in the external world.

Employee Nesting Benefitpackage

public partial class Employee

{

Benefitpackage Nesting Benefitpackagelevel

public class Benefitpackage

{

public enum Benefitpackagelevel

{Standard,gold,platinum}

}

Public double computepaydeduction ()

{return 125.0}

}

In this nesting relationship, you need to be aware of how enumerations are used:

Employee.BenefitPackage.BenefitPackageLevel Mybenefitlevel=employee.benefitpackage.benefitpackagelevel.platinum ;


Virtual and Override Keywords

Polymorphism provides a way for a subclass to be defined as a method defined by its base class, a process called method rewriting.

Partial class Employee

{

Poblic virtual void Givebonus (float amount)

{Pay+=amount;}

......

}

The method marked with the virtual keyword becomes a virtual method.

If a subclass wants to change the implementation details of a virtual method, it must use the Override keyword.

Class Salesperson:employee

{ .......

Sales people's bonuses are affected by sales

public override void Givebonus (float amount)

{

int salesbonus=0;

if (numberofsales>=0&&numberofsales<=100)

salesbonus=10;

Else

{if (numberofsales>=101&&numberofsales<=200)

salesbonus=15;

Else

salesbonus=20;

}

Base. Givebonus (Amount*salesbonus);

}

}

Class Manager:employee

{ .......

public override void Givebonus (float amout)

{base. Givebonus (amount);

Random r=new random ();

Numberofoptions+=r.next (500);

}

}


Sealing Virtual Members

Class Salesperson:employee

{  ........

public override sealed void Givebonus (float amount)

{  .......  }

}

Sealed class Ptsalesperson:salesperson

{ .......

Public Ptsalesperson (String fullname,int age,int empid,float currpay,string ssn,int numbofsales)

: Base (Fullname,age,empid,currpay,ssn,numbofsales)

{  }

Compiler Error! This method cannot be overridden in the Ptsalesperson class because it is sealed

public override void Givebonus (float amount)

{   }

}


Abstract class

Because many of the base classes are blurry corpses, good designers prevent the creation of new employee objects directly in the code.

Abstract partial class Employee

{   ........  }


Building a polymorphic interface

Member projection

Conversion rules for base class/derived classes


As keyword

We can't force the conversion of Frank to Hexagon, but the compilation is fine.

Hexagon hex= (Hexagon) Frank;

Using "as" to test compatibility

Hexagon Hex2=frank as Hexagon;

if (hex2==null)

Console.WriteLine ("Sorry,frank is not a Hexagon ...");


is keyword

In addition to the IS keyword, the C # language provides the IS keyword to test the compatibility of two items. However, unlike the AS keyword, if the type is incompatible, the IS keyword returns false instead of a null reference.


Super Parent class: System.Object

Core members of System.Object

Equals () By default, the method returns true if the item being compared points to the same item in memory. Therefore, Equals () is used to compare the object reference, not the state of the object. In general, this method is overridden to return true if the object being compared has the same internal state value (that is, value-based semantics). Be aware that if you override Equals (), you also need to override GetHashCode (), because these methods are used internally to read child objects from the container hashtable type. The ValueType class overrides this method for all structs, and the comparisons they make are value-based.

Finalize () This method (after rewriting) is called to release the allocated resource before the object is destroyed.

GetHashCode () This method returns an int to identify the specified object instance.

ToString () This method returns the string representation of an object in <namespace>,<type name> format (called fully qualified name). This method can be overridden by a quilt class to return the identity string of a name/value pair to represent the internal state of the object, rather than its fully qualified name.

GetType () This method returns the type object, which completely describes the object that is currently pointing. In short, this is the run-time type identification method that is available for all objects.

MemberwiseClone () The function of this method is to return a copy of the current object one by one, usually for cloning an object.

[Csharp]5 Inheritance and polymorphism

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.