Experience C # Lean replacement principles 10.6.24

Source: Internet
Author: User

We know that generics can store a parent class of the class type, so we can add its subclass. Many people may have questions about this. In principle, the subclass object can be assigned to the parent class object, that is, the subclass can completely replace the place where the parent class appears, but in turn the parent class object does not replace the subclass object. We call this feature LSP ).

There are two key words in the lee's replacement principle: Is and

1. Is is used to check whether the object is compatible with the given object type,

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;

Namespace istext
{
Class Program
{
Static void main (string [] ARGs)
{
Int I = 3;
String STR = "Hello World ";
If (I is string)
{
Console. writeline ("is a given type ");
}
Else
{
Console. Write ("not a given type ");
}
}
}
}
& No error message will be reported if the specified type is not determined.

2. The as operator is similar to forced type conversion. If the conversion fails, no error is reported. Only a null value is returned.

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;

Namespace istext
{
Class Program
{
Static void main (string [] ARGs)
{

String STR = "Hello World ";

Object S = STR as object;
If (s! = NULL)
{
Console. writeline ("conversion successful !!! ");
Console. writeline (S. tostring ());
}
Else
{
Console. writeline ("Conversion failed ");
}
}
}
}

 

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.