In this article I want to summarize my understanding of the IS and as operators to review the C # basics.
Is operator: Checks whether the object is compatible with the given type.
Description
1>: If the supplied expression is not empty, and the provided object can be cast to the supplied type without causing an exception to be thrown, the is expression evaluates to True, otherwise it returns false.
1): null expression: Return False
//表达式为空
object oo = null;
bool isstudent3 = oo is student;
2): expression content is not empty, but an exception occurred while casting the type, return False
oo = new object();
bool isstudent4 = oo is student;
3): When the expression is null, the exception is not thrown because there is no correct object to do type validation.
The 2>:is operator only considers reference conversions, boxing conversions, and unboxing conversions. The following program has a compile-time error (CTE): The known expression will always be true or always false
int i=5;
if (i is decimal )
{
//提示:给定表达式始终不是所提供的("decimal")类型
}
if (i is int)
{
//给定表达式始终为所提供的("int")类型
}
3>: The is operator cannot be overloaded.
4>: The first operand of the "is" or "as" operator cannot be a lambda expression or an anonymous expression.
if ((delegate(int i) { return i; }) is testdelegate)
{
//提示:"is"或"as"运算符的第一个操作数不能是lambda表达式 或匿名表达式
}
if (((x) => { return x; }) is testdelegate)
{
//提示:"is"或"as"运算符的第一个操作数不能是lambda表达式或匿名表达式
}