C # use is, as or explicit forced conversion for reference type conversion ?, Cf

Source: Internet
Author: User

C # use is, as or explicit forced conversion for reference type conversion ?, Cf

In C #, when the reference type needs to be converted, the keywords is, as, and explicit forced conversion are often used. This article describes how to use these three methods.

 

First, sort out the "Conventions" of. NET reference type conversion, or "Conventions ":
● Subclass can be implicitly converted to parent class/base class, that is, the class must be replaced by its parent class/base class.
● Explicit type conversion is required when the parent class/base class is converted to a subclass.

 

Convert subclass to parent class

class Program    {        static void Main(string[] args)        {            Animal animal = new Dog(){Name = "Dog",Age = 1};            Console.WriteLine(animal.Name);            Console.ReadKey();        }    }               public class Animal    {        public string Name { get; set; }    }    public class Dog : Animal    {        public int Age { get; set; }    }

Output result: Dog

 

As mentioned above, the sub-class is converted to the parent class, from which we can see that the sub-class Dog can indeed replace the parent class Animal. In other words, the sub-class is the parent class, sub-class instances can be assigned to the parent class variables, without the need for as, without strong conversion, everything is implicit, a good embodiment of the "Lee's replacement principle ".

 

The parent class is converted to a subclass. The parent class variable is created by assigning values to the subclass.

Parent class as Child class:

Animal animal = new Dog(){Name = "Dog",Age = 1};            Dog dog = animal as Dog;            Console.WriteLine(dog.Name + " " + dog.Age);            Console.ReadKey();

Output result: Dog 1

 

The parent class is explicitly converted to a subclass.

Animal animal = new Dog(){Name = "Dog",Age = 1};            Dog dog = (Dog)animal;            Console.WriteLine(dog.Name + " " + dog.Age);            Console.ReadKey();

Output result: Dog 1

In the preceding example, the parent class can be converted to a subclass either by using the as or explicit forced conversion, but the premise is that the subclass instance is assigned to the parent class variable.

 

The parent class is converted to a subclass. The parent class variable is created through its own constructor.

Failed to subclass the parent class:

Animal animal = new Animal(){Name = "Sheep"};            Dog dog = animal as Dog;            Console.WriteLine(dog.Name + " " + dog.Age);            Console.ReadKey();

Output result: the error "NullReferenceException" is returned.

It can be seen that when a parent class variable is created through its own constructor, the parent class cannot be converted to a subclass.

 

(1) In order to avoid the "NullReferenceException" error when the as is reported, the key is introduced for type determination:

Animal animal = new Animal () {Name = "Sheep"}; if (animal is Dog) {Dog dog = animal as Dog; Console. writeLine (dog. name + "" + dog. age);} else {Console. writeLine ("animal cannot be converted to Dog");} Console. readKey ();

Output result: animal cannot be converted to Dog.


(2) If the conversion fails when the as type conversion is performed, null is returned. Based on this, you can also determine whether the returned value after the as conversion is null to avoid the following error:

Animal animal = new Animal () {Name = "Sheep"}; Dog dog = animal as Dog; if (dog! = Null) {Console. writeLine (dog. name + "" + dog. age);} else {Console. writeLine ("animal cannot be converted to Dog");} Console. readKey ();

Output result: animal cannot be converted to Dog.

 

An error occurred while explicitly converting the parent class to a subclass.

Animal animal = new Animal(){Name = "Sheep"};            Dog dog = (Dog) animal;            Console.WriteLine(dog.Name + " " + dog.Age);            Console.ReadKey();

Output result: the error "InvalidCastException" is returned.

It can be seen that when a parent class variable is created through its own constructor, the parent class cannot be converted to a subclass.

To avoid the error "InvalidCastException" when displaying strong conversion, the keyword is introduced for type determination:

Animal animal = new Animal () {Name = "Sheep"}; if (animal is Dog) {Dog dog = (Dog) animal; Console. writeLine (dog. name + "" + dog. age);} else {Console. writeLine ("animal cannot be converted to Dog");} Console. readKey ();

Output result: animal cannot be converted to Dog.

 

Summary

● Explicit forced conversion or as should be considered for conversion of reference types. The difference between the two is: Once the type cannot be converted, an explicit strong transfer error is returned, and null is returned when the as is used.
● To avoid explicit forced conversion or as errors, use is to determine whether conversions can be performed between types.
● Using as to convert the reference type can not only use is to determine whether data types can be converted, but also determine whether the returned value after as is null, and then take appropriate actions.
● Conversion of basic types: Use Convert, Parse, and TryParse.

Is used to determine whether the types are consistent, as and explicit forced conversion is used for type conversion.


In C language ^ how to use a1 = 0x01; // 0000 0001
A2 = 0x00; // 0000 0000
A3 = 0x03; // 0000 0011
A4 = 0x02; // 0000 0010

B1 = a1 ^ a2; // 0000 0001
B2 = a1 ^ a3; // 0000 0010
B3 = a1 ^ a4; // 0000 0011

^ XOR operator. The bitwise value is the same as 0 and the bitwise value is the same as 1. See the example above.

//
Examples of simple and practical problems:
====================================
======= A ======= B =========
The above two circuits, two switches a and B, respectively. The opening status is \ [1]. The closing status is/[0].
If both are enabled or disabled, both circuits are connected.
If a turns on [1], B turns off [0], and circuit 1 Powers on
=====================
If a disables [0], B enables [1], and circuit 2 powers on.
====================================
In summary, when circuit a and circuit B are in the same State, the power is [0], a, and circuit B are powered on at the same time [1].
C Language & |! What are the variables used by the & access operator?
Compared with the definition of variable compilation, the system will allocate space in memory.
Space memory location address & extracted address
E. g int a; the address ratio allocated to the database during compilation is 2000; & a2000
False first defines the integer pointer variable pp = & a; assigns address a 2000 to p to run p = 2000
Scanf ("% d", & a); when entering 3, the system will first find the memory space of a from the address according to & a, and then write 3 into the space.
* The pointer operator is used to retrieve variable values based on the variable address.
Compare to * a value variable a value 3
The following is a summary of definitions and declarations using pointers.
Int * p; Define pointer to integer data
Int * p [n]; the defined pointer array p is composed of n elements pointing to the Integer Data Pointer.
Int (* p) [n]; p points to the array pointer variable containing the nelement dimension
Int * p (); p returns the pointer function. This Pointer Points to integer data.
Int (* p) (); p points to the function pointer. This function returns an integer value.
Int ** p; p pointer variable pointing to Integer Data Pointer variable
For more information about the system, see Tan haoqiang's c Programming (the third edition). This book is easy to understand and learn c language errors.

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.