C # object looks like a dynamic type

We played with 4.0 DLR and compared the dynamics with the object and came across this:

the code:

object x = 10;
            Console.WriteLine("x = {0} and is a {1}.\n", x, x.GetType());
            x = (int)x + 3;
            Console.WriteLine("x = {0} and is a {1}.\n", x, x.GetType());
            x = x + "a";
            Console.WriteLine("x = {0} and is a {1}.\n", x, x.GetType());

Result:

x = 10 and is System.Int32.

x = 13 and is System.Int32.

x = 13a and is System.String.

It seems to me that the object is trying to bind the object to a type at runtime (dynamic). However, if I don't pass x to int on the third line, this gives me a compiler area that seems correct for static input. But then it lets me add "a" to x, and now it recognizes it as a string.

What am I missing?

+5
source share
7 answers

, +, , ( .ToString() , String).

+6

#:

7.8.4

, .

  • :

    string operator +(string x, string y);
    string operator +(string x, object y);
    string operator +(object x, string y);
    

    binary + . null, . , ToString, . ToString null, .

+4

, ().

: .NET object .

dynamic, - ,

dynamic x = "hello";
dynamic y = x.Substring(0, 2); // The compiler does not complain

"" object, . dynamic , , .

"a" x, .

" ", : , object ToString .

+1

, ( object) , .

, System.String , object ToString().

.

+1

#, object, .

object x = 10;
x = x + "a";

, . object .ToString(), +, .

IL ,

  .locals init ([0] object x)
  IL_0000:  nop
  IL_0001:  ldc.i4.s   10
  IL_0003:  box        [mscorlib]System.Int32
  IL_0008:  stloc.0
  IL_0009:  ldloc.0
  IL_000a:  ldstr      "a"
  IL_000f:  call       string [mscorlib]System.String::Concat(object,
                                                              object)

String.Concat string .

# 5.0 :

  • :

    string operator +(string x, string y);
    string operator +(string x, object y);
    string operator +(object x, string y);
    

    binary + . null, . , ToString, . ToString null, .

+1

# object. int, string, char .. .

:

object x = 10;

, x, 10. int, boxed .

x int, unboxing .

Unboxing

0

#, "",

0

All Articles