gpt4 book ai didi

c# - 在 C# 中需要 IS 运算符

转载 作者:太空宇宙 更新时间:2023-11-03 17:24:00 25 4
gpt4 key购买 nike

<分区>

在 C# 中有 is 运算符用于检查对象是否与某种类型兼容。此运算符尝试将对象转换为某种类型,如果转换成功,则返回 true(如果转换失败,则返回 false)。

来自 Jeffrey Richter CLR via C#:

The is operator checks whether an object is compatible with a given type, and the result of the evaluation is a Boolean: true or false.

if (o is Employee) 
{
Employee e = (Employee) o;
// Use e within the remainder of the 'if' statement.
}

In this code, the CLR is actually checking the object’s type twice: The is operator first checks to see if o is compatible with the Employee type. If it is, inside the if statement, the CLR again verifies that o refers to an Employee when performing the cast. The CLR’s type checking improves security, but it certainly comes at a performance cost, because the CLR must determine the actual type of the object referred to by the variable (o), and then the CLR must walk the inheritance hierarchy, checking each base type against the specified type (Employee).

另外,来自同一本书:

Employee e = o as Employee;
if (e != null)
{
// Use e within the 'if' statement.
}

In this code, the CLR checks if o is compatible with the Employee type, and if it is, as returns a non-null reference to the same object. If o is not compatible with the Employee type, the as operator returns null. Notice that the as operator causes the CLR to verify an object’s type just once. The if statement simply checks whether e is null; this check can be performed faster than verifying an object’s type.

所以,我的问题是:为什么我们需要 is 运算符?在哪些情况下 is 运算符比 as 更可取。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com