52

Consider these functions:

static void Take(object o)
{
    Console.WriteLine("Received an object");
}

static void Take(int i)
{
    Console.WriteLine("Received an integer");
}

When I call the Take function this way:

var a = (object)2;
Take(a);

I get :Received an object

But if call it like:

dynamic b = (object) 2;
Take(b);

I get:Received an integer

Both parameters (a & b) are cast to object. But why compiler has this behavior?

4

6 回答 6

55

var只是让RHS决定类型的语法糖。

在您的代码中:

var a = (object)2;

相当于:

object a = (object)2;

你得到一个对象,因为你装箱2到一个对象。

对于dynamic,您可能想看看Using Type dynamic。请注意,该类型是静态类型,但动态类型的对象绕过静态类型检查,即您指定的类型:

dynamic b = (object) 2;

被绕过,它的真实类型在运行时被解析。


对于它在运行时是如何解决的,我相信它比你想象的要复杂得多..

假设您有以下代码:

public static class TestClass {
    public static void Take(object o) {
        Console.WriteLine("Received an object");
    }

    public static void Take(int i) {
        Console.WriteLine("Received an integer");
    }

    public static void TestMethod() {
        var a=(object)2;
        Take(a);

        dynamic b=(object)2;
        Take(b);
    }
}

我将完整的 IL(调试配置)放在答案的后面。

对于这两行:

var a=(object)2;
Take(a);

IL 只有:

IL_0001: ldc.i4.2
IL_0002: box [mscorlib]System.Int32
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: call void TestClass::Take(object)

但是对于这两个:

dynamic b=(object)2;
Take(b);

是从IL_000fIL_007aTestMethod它不直接调用Take(object)or Take(int),而是像这样调用方法:

object b = 2;
if (TestClass.<TestMethod>o__SiteContainer0.<>p__Site1 == null)
{
    TestClass.<TestMethod>o__SiteContainer0.<>p__Site1 = CallSite<Action<CallSite, Type, object>>.Create(Binder.InvokeMember(CSharpBinderFlags.ResultDiscarded, "Take", null, typeof(TestClass), new CSharpArgumentInfo[]
    {
        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, null),
        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
    }));
}
TestClass.<TestMethod>o__SiteContainer0.<>p__Site1.Target(TestClass.<TestMethod>o__SiteContainer0.<>p__Site1, typeof(TestClass), b);

的完整 IL TestClass

.class public auto ansi abstract sealed beforefieldinit TestClass
    extends [mscorlib]System.Object
{
    // Nested Types
    .class nested private auto ansi abstract sealed beforefieldinit '<TestMethod>o__SiteContainer0'
        extends [mscorlib]System.Object
    {
        .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
            01 00 00 00
        )
        // Fields
        .field public static class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Action`3<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>> '<>p__Site1'

    } // end of class <TestMethod>o__SiteContainer0


    // Methods
    .method public hidebysig static 
        void Take (
            object o
        ) cil managed 
    {
        // Method begins at RVA 0x2050
        // Code size 13 (0xd)
        .maxstack 8

        IL_0000: nop
        IL_0001: ldstr "Received an object"
        IL_0006: call void [mscorlib]System.Console::WriteLine(string)
        IL_000b: nop
        IL_000c: ret
    } // end of method TestClass::Take

    .method public hidebysig static 
        void Take (
            int32 i
        ) cil managed 
    {
        // Method begins at RVA 0x205e
        // Code size 13 (0xd)
        .maxstack 8

        IL_0000: nop
        IL_0001: ldstr "Received an integer"
        IL_0006: call void [mscorlib]System.Console::WriteLine(string)
        IL_000b: nop
        IL_000c: ret
    } // end of method TestClass::Take

    .method public hidebysig static 
        void TestMethod () cil managed 
    {
        // Method begins at RVA 0x206c
        // Code size 129 (0x81)
        .maxstack 8
        .locals init (
            [0] object a,
            [1] object b,
            [2] class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo[] CS$0$0000
        )

        IL_0000: nop
        IL_0001: ldc.i4.2
        IL_0002: box [mscorlib]System.Int32
        IL_0007: stloc.0
        IL_0008: ldloc.0
        IL_0009: call void TestClass::Take(object)
        IL_000e: nop
        IL_000f: ldc.i4.2
        IL_0010: box [mscorlib]System.Int32
        IL_0015: stloc.1
        IL_0016: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Action`3<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>> TestClass/'<TestMethod>o__SiteContainer0'::'<>p__Site1'
        IL_001b: brtrue.s IL_0060

        IL_001d: ldc.i4 256
        IL_0022: ldstr "Take"
        IL_0027: ldnull
        IL_0028: ldtoken TestClass
        IL_002d: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
        IL_0032: ldc.i4.2
        IL_0033: newarr [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo
        IL_0038: stloc.2
        IL_0039: ldloc.2
        IL_003a: ldc.i4.0
        IL_003b: ldc.i4.s 33
        IL_003d: ldnull
        IL_003e: call class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo::Create(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)
        IL_0043: stelem.ref
        IL_0044: ldloc.2
        IL_0045: ldc.i4.1
        IL_0046: ldc.i4.0
        IL_0047: ldnull
        IL_0048: call class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo::Create(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)
        IL_004d: stelem.ref
        IL_004e: ldloc.2
        IL_004f: call class [System.Core]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::InvokeMember(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, class [mscorlib]System.Collections.Generic.IEnumerable`1<class [mscorlib]System.Type>, class [mscorlib]System.Type, class [mscorlib]System.Collections.Generic.IEnumerable`1<class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)
        IL_0054: call class [System.Core]System.Runtime.CompilerServices.CallSite`1<!0> class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Action`3<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>>::Create(class [System.Core]System.Runtime.CompilerServices.CallSiteBinder)
        IL_0059: stsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Action`3<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>> TestClass/'<TestMethod>o__SiteContainer0'::'<>p__Site1'
        IL_005e: br.s IL_0060

        IL_0060: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Action`3<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>> TestClass/'<TestMethod>o__SiteContainer0'::'<>p__Site1'
        IL_0065: ldfld !0 class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Action`3<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>>::Target
        IL_006a: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Action`3<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>> TestClass/'<TestMethod>o__SiteContainer0'::'<>p__Site1'
        IL_006f: ldtoken TestClass
        IL_0074: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
        IL_0079: ldloc.1
        IL_007a: callvirt instance void class [mscorlib]System.Action`3<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object>::Invoke(!0, !1, !2)
        IL_007f: nop
        IL_0080: ret
    } // end of method TestClass::TestMethod

} // end of class TestClass
于 2013-06-25T07:33:40.290 回答
15

动态的:

  1. dynamic是一个Dynamically typed
  2. 动态类型 - 这意味着声明的变量类型由编译器在运行时决定。

变量:

  1. var是一个Statically typed
  2. 静态类型——这意味着声明的变量类型由编译器在编译时决定。

通过这种方式,您会看到在运行时发生重载解决方案dynamic

所以变量b保持为int

dynamic b = (object) 2;
Take(b);

Take(b);这就是打电话的原因Take(int i)

static void Take(int i)
    {
        Console.WriteLine("Received an integer");
    }

但在 的情况下var a = (object)2,变量a保持为“对象”

var a = (object)2;
Take(a);

这就是为什么 Take(a); 来电Take(object o)

static void Take(object o)
    {
        Console.WriteLine("Received an object");
    }
于 2013-06-25T07:17:29.273 回答
2

装箱整数参数解析发生在编译时。这是IL:

IL_000d:  box        [mscorlib]System.Int32
IL_0012:  stloc.0
IL_0013:  ldloc.0
IL_0014:  call       void ConsoleApp.Program::Take(object)

object您可以看到它在编译时本身已解决为重载。

当您使用dynamic时 - 运行时活页夹就出现了。dynamic不仅可以解析为托管的 C# 对象,还可以解析为非托管对象,例如 COM 对象或 JavaScript 对象,前提是这些对象存在运行时绑定器。

我不会显示 IL,而是显示反编译的代码(更易于阅读):

   object obj3 = 2;
        if (<Main>o__SiteContainer0.<>p__Site1 == null)
        {
            <Main>o__SiteContainer0.<>p__Site1 = CallSite<Action<CallSite, Type, object>>.Create(Binder.InvokeMember(CSharpBinderFlags.ResultDiscarded, "Take", null, typeof(Program), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.IsStaticType | CSharpArgumentInfoFlags.UseCompileTimeType, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));
        }
        <Main>o__SiteContainer0.<>p__Site1.Target(<Main>o__SiteContainer0.<>p__Site1, typeof(Program), obj3);

您会看到该Take方法在运行时由运行时绑定程序而不是由编译器解析。因此,它会将其解析为实际类型。

于 2013-06-25T08:00:03.757 回答
1

如果您查看 C# 规范:

1.6.6.5 方法重载

方法重载允许同一类中的多个方法具有相同的名称,只要它们具有唯一的签名即可。在编译重载方法的调用时,编译器使用重载决议来确定要调用的特定方法。

和:

7.5.4 动态重载解析的编译时检查

对于大多数动态绑定操作,可能的解析候选集在编译时是未知的。然而,在某些情况下,候选集在编译时是已知的:

  • 使用动态参数调用静态方法

  • 接收者不是动态表达式的实例方法调用

  • 接收者不是动态表达式的索引器调用

  • 带有动态参数的构造函数调用

在这些情况下,对每个候选者执行有限的编译时检查,以查看它们中的任何一个是否可能在运行时应用

因此,在您的第一种情况下,var它不是动态的,重载解析会在compile-time找到重载方法。

但是在第二种情况下,您正在使用动态参数调用静态方法重载解析将在运行时找到重载方法

于 2013-06-25T07:43:13.353 回答
1

帮助理解动态变量的类型解析。

  • 首先在该行放置一个断点:

    Take(b); //See here the type of b when u hover mouse over it, will be int

这显然意味着代码:dynamic b = (object)2分配给动态变量时不会将 2 转换为对象,并且 b 仍然是 int

  • 接下来,注释掉你的Take(int i)方法重载,然后在 line 上放置一个断点Take(b)(相同:type of bis still int)但是当你运行它时,你会看到打印的值是:Recieved object。

  • 现在,将您的dynamic变量调用更改为以下代码:

    Take((object)b); //It now prints "Received an object"

  • 接下来,将您的调用更改为以下代码并查看返回的内容:

    dynamic b = (long)2;

    Take(b); // It now prints Received an object because there is no method overload that accepts a long and best matching overload is one that accepts an目的.

这是因为:动态变量的最佳匹配类型是根据它在运行时持有的值来解析的,并且要调用的最佳匹配重载方法也是在运行时为动态变量解析的。

于 2013-06-25T07:51:00.693 回答
0

在第一种情况下, var 表示object如此Take(object o)调用。在第二种情况下,您使用dynamictype 并且尽管您已将您的框装箱,但int它仍然具有有关其类型的信息 -int因此调用了最佳匹配方法。

于 2013-06-25T07:25:13.273 回答