使用动态输入参数和对象声明为 return 类型的方法实际上是 returns 动态

Method declared with dynamic input parameter and object as return type in fact returns dynamic

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var objectGetter = new ObjectGetter();
      var obj = objectGetter.GetItem(); //Visual Studio shows that obj type is System.Object
    }
  }

  public class ObjectGetter
  {
    public object GetItem()
    {
      dynamic dObj = "123";
      var obj = this.Convert(dObj);//Visual Studio shows that obj type is "dynamic" here. why???
      return obj;
    }

    private object Convert(dynamic dObj)
    {
      return new object();
    }
  }
}

我预计 Convert 方法调用将 return System.Object 但实际上它 return 是 dynamic。我不明白为什么。

您可以尝试使用任何 return 类型,但结果是一样的。

问题是您正在调用带有 dynamic 参数的方法。这意味着它是动态绑定的,并且 return 类型被认为是动态的。你需要做的就是不要那样做:

object dObj = "123";
var obj = Convert(dObj);

然后 Convert 调用将被静态绑定,并且 obj 将具有 object.

的类型

来自 C# 5 规范,第 7.6.5 节:

An invocation-expression is dynamically bound (§7.2.2) if at least one of the following holds:

  • The primary-expression has compile-time type dynamic.
  • At least one argument of the optional argument-list has compile-time type dynamic and the primary-expression does not have a delegate type.

In this case the compiler classifies the invocation-expression as a value of type dynamic.