动态参数导致编译器认为方法返回是动态的 [英] Dynamic parameter causes compiler to think method return is dynamic

查看:16
本文介绍了动态参数导致编译器认为方法返回是动态的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个动态参数,编译器似乎会放弃返回类型并认为它是动态的.

If I have a dynamic parameter the compiler seems to ditch the return type and think it's dynamic.

例如:

public MethodResult IsValid(object userLogin)
{     
  return new MethodResult();
}

你会认为:

var isValidResult = IsValid(someObject());

应该读作

dynamic -> MethodResult 

但它认为是:

dynamic -> dynamic

尽管返回是强类型的,但向签名添加动态参数是否会完全阻止编译器知道返回应该是什么?

Does adding a dynamic parameter to the signature completely stop the compiler from knowing what the return should be despite the return being strongly typed?

推荐答案

是的,动态会阻止编译器了解任何参数、属性或方法返回类型的类型.添加显式转换,如:

Yes, dynamic stops the compiler from knowing the type on any parameters, properties, or method return types. Add an explicit cast like:

(MethodResult)IsValid(someObject));

这里的原因是,一旦您在 C# 中进入动态世界,您就会进入后期绑定.编译器无法验证此代码,因为它不能再使用任何静态类型分析.所以它推迟到以后.您可以通过提供静态强制转换作为编译器的指南来帮助克服这个问题.

The reason here is that once you enter the dynamic world in C# you are going into late binding. The compiler can't verify this code because it can no longer use any static type analysis. So it defers until later. You can help overcome this by providing static casts as a guide for the compiler.

这篇关于动态参数导致编译器认为方法返回是动态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆