C#的is关键字

来源:互联网 发布:st单片机 编辑:程序博客网 时间:2024/05/16 14:17

Checks if an object is compatible with a given type. For example, it can be determined if an object is compatible with the string type like this:

if (obj is string){}
Remarks

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown. For more information, see 7.6.6 Cast expressions.

The is keyword results in a compile-time warning if the expression is known to always be true or to always be false, but typically evaluates type compatibility at run time.

The is operator cannot be overloaded.

Note that the is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered.

Example

// cs_keyword_is.cs// The is operator.using System;class Class1{}class Class2{}class IsTest{    static void Test(object o)    {        Class1 a;        Class2 b;        if (o is Class1)        {            Console.WriteLine("o is Class1");            a = (Class1)o;            // Do something with "a."        }        else if (o is Class2)        {            Console.WriteLine("o is Class2");            b = (Class2)o;            // Do something with "b."        }        else        {            Console.WriteLine("o is neither Class1 nor Class2.");        }    }    static void Main()    {        Class1 c1 = new Class1();        Class2 c2 = new Class2();        Test(c1);        Test(c2);        Test("a string");    }}

Output

 
o is Class1o is Class2o is neither Class1 nor Class2.
原创粉丝点击