C#"是"运营商 - 是反思? [英] C# "is" operator - is that reflection?

查看:140
本文介绍了C#"是"运营商 - 是反思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个同事问我今天一个有趣的问题 - 在C#的关键字/操作员被认为是反射

A colleague asked me an interesting question today - is the C# keyword/operator "is" considered reflection?

object tmp = "a string";
if(tmp is String)
{
}



如何这是运营商在幕后执行?是否需要反思自省还是?或由于语言的强类型的性质,是对象的类型立即accessable作为在存储器中的对象的顶层属性

How is this operator implemented behind the scenes? Does it require reflection or introspection? Or because of the strongly typed nature of the language, is the Type of the object immediately accessable as a top-level attribute of the object in memory?

MSDN 指出:

注意,是运营商只考虑引用转换,装箱转换,和拆箱转换。其他转换,如用户定义的转换,不是由是运营商考虑的。

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

考虑装箱和拆箱转换的能力,似乎暗示给我某种反省。

The ability to consider boxed and unboxed conversions seems to imply to me some sort of introspection.

推荐答案

引用ECMA-335 ,在运算生成 isinst 对象模型。IL指令(分区III§4.6),这是相对于作为反射库(分区四§5.5)的一部分设置的基本指令的一部分

Referencing ECMA-335, the is operator generates the isinst object model IL instruction (Partition III §4.6), which is part of the base instruction set as opposed to being part of the Reflection library (Partition IV §5.5).

编辑:相比反射库运营商是非常有效的。你可以通过反射基本上是相同的测试速度要慢得多执行:

The is operator is extremely efficient compared to the reflection library. You could perform basically the same test much more slowly via reflection:

typeof(T).IsAssignableFrom(obj.GetType())

编辑2:你是不是对 castclass isinst 的说明(您现在已经修改了帖子)。它们在任何实际VM实现高度优化。所涉及的唯一真正的性能问题是潜在的 castclass 抛出一个异常,你可以通过使用C#来避免运营商和测试(引用类型)或操作符后跟一个CAST(值类型)

Edit 2: You are not correct about the efficiency of the castclass and isinst instructions (which you've now edited out of the post). They are highly optimized in any practical VM implementation. The only real performance issue involved is the potential for castclass to throw an exception, which you avoid by using the C# as operator and a test for null (for reference types) or the is operator followed by a cast (for value types).

这篇关于C#"是"运营商 - 是反思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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