How to use c # IS and

Source: Internet
Author: User

// Solution: in many cases, we do not know whether the object supports an interface. In this case, we can try to convert the object to an interface type.
// In c #, we can use either of the following methods to obtain an object that supports an interface:

The Code is as follows:

 

Using System;
Using System. Collections. Generic;
Using System. Text;

Namespace ConsoleApplication6
{
Class Program
{
Static void Main (string [] args)
{
Conn cn = new conn ();
If (cn is Iconnect) // whether the interface is implemented
{
Iconnect iconn = (Iconnect) cn;
Iconn. read ();
Console. ReadLine ();
}
Else
{
Console. WriteLine ("can not connvert ");
Console. ReadLine ();
}

// The IS operator IS clear, but the operation efficiency IS not high. The other method IS

Conn cnn = new conn ();
Iconnect icnn1 = cnn as Iconnect;
If (icnn1! = Null)
{
Icnn1.write ();
Console. ReadLine ();
}
Else
{
Console. WriteLine ("can not connvert ");
Console. ReadLine ();
}
// The as operator first tests whether the conversion is legal. If the conversion is legal, the conversion is performed. Otherwise, NULL is returned. Keyword NULL indicates NULL reference
}
}

Public interface Iconnect
{
Void read ();
Void write ();
}

Public class conn: Iconnect
{
Public void read ()
{
Console. WriteLine ("read () method implemented ");
}
Public void write ()
{
Console. WriteLine (
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.