gpt4 book ai didi

c# - "as"关键字在内部是如何工作的?

转载 作者:太空狗 更新时间:2023-10-29 18:00:28 25 4
gpt4 key购买 nike

我知道这个关键字的作用,但我想知道它在较低层次上是如何工作的。

哪个更快?它们总是产生相同的结果吗?如果他们这样做,为什么会有两种不同的方式?

// Is there an overhead? An internal try catch?
Class123 obj = someobject as Class123;

if (Class123 != null)
{
//OK
}

Class123 obj = null;

if (someobject is Class123)
{
obj = (Class123)someobject;
}

最佳答案

根据 MSDN: as (C# Reference) :

The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception. Consider the following expression:

expression as type

It is equivalent to the following expression except that expression is evaluated only one time.

expression is type ? (type)expression : (type)null

第一个变体(作为操作数)...

string str1 = strAsObject as string;
if (str1 != null)
{
this.blabla(str1);
}

...编译成这个 IL 代码:

L_0009: ldloc.1 
L_000a: isinst string
L_000f: stloc.2
L_0010: ldloc.2
L_0011: ldnull
L_0012: ceq
L_0014: stloc.s CS$4$0000
L_0016: ldloc.s CS$4$0000
L_0018: brtrue.s L_0024
L_001a: nop
L_001b: ldarg.0
L_001c: ldloc.2
L_001d: call instance void TestWinFormsApplication001.Form1::blabla(string)
L_0022: nop
L_0023: nop

... 和第二个变体(是操作数 + cast)...

if (strAsObject is string)
{
string str2 = (string) strAsObject;
this.blabla(str2);
}

...编译成这个 IL 代码:

L_0024: ldloc.1 
L_0025: isinst string
L_002a: ldnull
L_002b: cgt.un
L_002d: ldc.i4.0
L_002e: ceq
L_0030: stloc.s CS$4$0000
L_0032: ldloc.s CS$4$0000
L_0034: brtrue.s L_0047
L_0036: nop
L_0037: ldloc.1
L_0038: castclass string
L_003d: stloc.3
L_003e: ldarg.0
L_003f: ldloc.3
L_0040: call instance void TestWinFormsApplication001.Form1::blabla(string)
L_0045: nop
L_0046: nop

...所以您看到的唯一区别是 L_0038 行中的附加 castclass 代码。

关于c# - "as"关键字在内部是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/955347/

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