C# “is” operator - is that reflection?

前端 未结 3 432
深忆病人
深忆病人 2020-12-29 02:42

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

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


        
相关标签:
3条回答
  • 2020-12-29 03:32

    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).

    Edit: 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())
    

    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).

    0 讨论(0)
  • 2020-12-29 03:46

    Other languages have runtime time information sufficient to support dynamic casting, and yet nothing that could be described as reflection (C++ being an obvious example).

    So reflection refers to additional capabilities beyond merely discovering the type of an object. To "reflect" on an object implies the ability to walk its members, for example.

    0 讨论(0)
  • 2020-12-29 03:48

    The is operator essentially determines if a cast is possible, but instead of throwing an exception when the cast is impossible it returns false. If you consider casting reflection then this is also reflection.

    EDIT:

    After some research I have discovered that a cast is performed in IL på the castclass instruction while the is operator maps to the isinst instruction. FxCop has a rule that warns you if you are doing unecessary casts by first using the isinst and then the castclass instruction. Even though the operations are efficient they still have a performance cost.

    0 讨论(0)
提交回复
热议问题