简体   繁体   English

“是”运算符如何与动态对象一起使用?

[英]How does the “is” operator work with dynamic objects?

How does the is operator work with respect to the DLR? 如何将is关于DLR运营商的工作?

To make my question a little more explicit, consider the following signature: 为了使我的问题更加明确,请考虑以下签名:

 public bool Is<T>(Func<dynamic> getInstance)
 { 
     return getInstance() is T;
 }

By default, what conditions are necessary for Is<T> to return true ? 默认情况下, Is<T>返回true需要什么条件? Furthermore, does the DLR provide any mechanism to customize this behavior? 此外,DLR是否提供任何机制来定制此行为?

At runtime, dynamic is treated the same as object , which means that the runtime type of the getInstance delegate's result will be used to perform this check. 在运行时, dynamic被视为与object相同,这意味着getInstance委托的结果的运行时类型将用于执行此检查。 The only difference using dynamic here will cause is that there will be no compile time checking, and dynamic binding will be used at runtime to perform this check on the dynamic object returned by getInstance . 这里使用dynamic的唯一区别是将不会进行编译时检查,并且将在运行时使用动态绑定对getInstance返回的动态对象执行此检查。

By default, what conditions are necessary for Is to return true? 默认情况下,Is返回true需要什么条件?

The delegate passed in will need to return a type which, at runtime, is compatible with T . 传入的委托将需要返回一个类型,该类型在运行时与T兼容。

Furthermore, does the DLR provide any mechanism to customize this behavior? 此外,DLR是否提供任何机制来定制此行为?

No. This is going to use the standard rules for C# types. 不会。这将使用C#类型的标准规则。 Any custom behavior would need to be written into the logic itself. 任何自定义行为都需要写入逻辑本身。

Since is already is a runtime test, there is no extra runtime binding being done, in fact there won't be any compiled IL difference to 既然is已经是一个运行测试,没有任何多余的运行时绑定正在做的,其实不会有任何编译IL差

 public bool Is<T>(Func<object> getInstance)
 { 
     return getInstance() is T;
 }

The IL for the method body of both Is<T>(Func<object> getInstance) and Is<T>(Func<dynamic> getInstance) : 两个方法体的IL Is<T>(Func<object> getInstance)Is<T>(Func<dynamic> getInstance)

    .maxstack 2
    .locals init (
        [0] bool CS$1$0000)
    L_0000: nop 
    L_0001: ldarg.1 
    L_0002: callvirt instance !0 [mscorlib]System.Func`1<object>::Invoke()
    L_0007: isinst !!T
    L_000c: ldnull 
    L_000d: cgt.un 
    L_000f: stloc.0 
    L_0010: br.s L_0012
    L_0012: ldloc.0 
    L_0013: ret 

So the answer is that is keyword is not effected by the usage of the DLR, it works the same as if you use the type object . 所以答案是, is的关键字不是由DLR的使用实现的,它的工作原理一样,如果你使用的类型object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM