“ as”如何进行?关键字在内部工作? [英] How does the "as" keyword work internally?

查看:79
本文介绍了“ as”如何进行?关键字在内部工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道此关键字的功能,但我想知道它在较低级别上如何工作。

I know the function of this keyword, but I would like to know how it works on a lower level.

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

Which one is faster? And do they always yield the same result? If they do, why are there two different ways?

// 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;
}


推荐答案

没有内部try-catch使用 as 关键字时发生的情况。据我所知,该功能是内置于编译器/ CLR中的,因此类型检查是隐式且自动化的。

There's no internal try-catch happening when using the as keyword. The functionality is built in to the compiler/CLR, as far as I know, so the type check is implicit and automated.

简单规则

当您总是希望对象具有已知类型时,请使用直接强制转换(因此,如果,则可能会收到有用的错误提示类型错误)。当对象始终是已知类型的对象时,请使用 as 关键字。

Simple rule:
Use a direct cast when you always expect the object to have a known type (and thus receive a helpful error if it is by chance of the wrong type). Use the as keyword when the object is always of a known type.

as 关键字存在的原因纯粹是为了程序员的方便(尽管您正确地建议try-catch会更慢)。如您所指出的那样,您可以自己手动实现它:

The reason for the existance of the as keyword is purely for the convenience of the programmer (although you are correct in suggesting that a try-catch would be slower). You could implement it yourself manually as such, as you point out:

var castObj = (obj is NewType) ? (NewType)obj : null;

这突显了事实,即 as关键字主要是出于简洁的目的而存在。

This highlights the fact that the 'as' keyword is primarily there for the purpose of conciseness.

现在,两者之间的性能差异可能微不足道。由于类型检查, as 关键字可能会稍微慢一些,但这在大多数情况下不太可能影响代码。如常说的那样,过早的优化绝不是明智的选择。如果您确实愿意,可以使用基准测试,但是我建议您只使用适合您情况的更方便/更合适的方法,而不用担心性能(或者如果绝对需要,则不要担心)。

Now, the performance difference between the two is likely to be negligible. The as keyword is probably marginally slower because of the type check, but this is unlikely to affect code in the vast majority of situations. As oft said, premature optimisation is never a wise thing to be doing. Benchmark if you really wish, but I would advise just to use whichever method is more convenient/appropiate for your situation, and not worry about performance at all (or later if you absolutely must).

这篇关于“ as”如何进行?关键字在内部工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆