dynamic vs object keyword on method params and return type

前端 未结 2 1109
忘掉有多难
忘掉有多难 2021-01-28 22:16

A very basic question, consider this methods:

public object Foo(object bar) {... }

vs

public dynamic Bar(dynamic bar) {... }
         


        
2条回答
  •  鱼传尺愫
    2021-01-28 22:55

    dynamic in C# is translated to object in IL.

    .method private hidebysig instance object Foo(object bar) cil managed
    {...}
    
    .method private hidebysig instance object Bar(object bar) cil managed
    {
      .param [0]
      .custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor() = ( 01 00 00 00 ) 
      .param [1]
      .custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor() = ( 01 00 00 00 ) 
      ...
    }
    

    The signature stays the same, only the Dynamic attribute is added to the return and first parameter.

    If you can change the parameter type from dynamic to object without having to change any other code, do it.

提交回复
热议问题