【问题标题】:Why this compiler error when mixing C# ValueTuple and dynamic为什么在混合 C# ValueTuple 和动态时出现此编译器错误
【发布时间】:2018-01-05 04:12:42
【问题描述】:

当使用ValueTuple 和动态对象时,我收到了这个奇怪的CS8133 错误。我将动态对象作为输入传递,并将 ValueTuple 作为输出。为什么会互相影响。

public static (string, string) foo(dynamic input)
{
    return ("", "");
}

public void foo_test()
{
    dynamic input = new { a = "", b = "" };
    (string v1, string v2) = foo(new { a = "", b = "" }); //compiles fine
    (string v3, string v4) = foo(input); //CS8133 Cannot deconstruct dynamic objects
    var result = foo(input);  //compiles fine
}

编辑: 错误信息是:CS8133 Cannot deconstruct dynamic objects

【问题讨论】:

  • 错误信息是什么?
  • foo(input) -> foo((object)input)
  • @PetSerAl 但为什么。为什么编译器只在第二次调用时报错
  • @XiaoguoGe 调用foodynamic 参数(input),因此它是通过动态绑定完成的,有dynamic 返回类型,但没有(string, string)

标签: c# dynamic roslyn c#-7.0


【解决方案1】:

the feature spec

解析相当于键入rhs.Deconstruct(out var x1, out var x2, ...); 并带有适当数量的参数来解构。它基于正常的过载解决方案。这意味着 rhs 不能是动态的,并且 Deconstruct 方法的任何参数都不能是类型参数。 ...

重要的部分是var。 在正常的重载决议中,我们可以从发现的Deconstruct 方法推断类型。但是通过动态方法调用,您无法获得编译时类型信息,因此var 类型必然无法推断(即,这是一个错误)。

更一般地说,这就是为什么您不能在动态调用中使用out var(out var local 的var 类型是什么?)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-17
    • 2013-08-14
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    相关资源
    最近更新 更多