简体   繁体   English

function 的动态参数 C# 改变它的返回类型

[英]C# dynamic parameter of a function changes it return type

A simple code一个简单的代码

dynamic v = "";
var a = F("");
var b = F(v);

static bool F(dynamic o) => true;

the type of variable a is bool, but b is dynamic instead of bool, why?变量a的类型是bool,但是b是动态的而不是bool,为什么?

The think the short answer is that once you declare a dynamic , the dynamic "behavior" (?) will continue to propagate through all future references to it until you explicitly resolve it.简短的回答是,一旦您声明了dynamicdynamic “行为”(?)继续通过所有未来的引用传播,直到您明确解决它。

It's not that the return type of F(o) has changed, it's that the compiler simply doesn't care anymore.并不是F(o)的返回类型发生了变化,而是编译器根本不在乎。

The declaration of a dynamic variable has disabled compile-time type-checking for all future references to that variable...again, until (or unless) it's explicitly resolved. dynamic变量的声明已禁用编译时对该变量的所有引用的类型检查......再次,直到(或除非)它被明确解决。

I am looking forward to reading other explanations, however.但是,我期待阅读其他解释。

The initial assertion that “the type of variable a is bool, but b is dynamic instead of bool” is not correct for a valid C# compiler, nor is it illustrated with the code.对于有效的 C# 编译器,“变量 a 的类型是 bool,但 b 是动态而不是 bool”的初始断言是不正确的,也没有用代码说明。

The following program will fail to compile, showing that b is indeed a bool See https://dotnetfiddle.net/E6fn0P to run the code.以下程序将无法编译,表明 b 确实是一个boolhttps://dotnetfiddle.net/E6fn0P运行代码。

using System;
                    
public class Program
{
    public static void Main()
    {
        static bool F(dynamic o) => true;
        
        dynamic v = "";
        var a = F("");
        var b = F(v);
        _ = b.Foo;

        Console.WriteLine("Hello World");
    }
}

The expected compiler error is:预期的编译器错误是:

Compilation error (line 12, col 13): 'bool' does not contain a definition for 'Foo' and no accessible extension method 'Foo' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?)编译错误(第 12 行,第 13 列): “bool”不包含“Foo”的定义,并且找不到接受“bool”类型的第一个参数的可访问扩展方法“Foo”(您是否缺少 using 指令或装配参考?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM