dynamic.ToString()意外行为 [英] dynamic.ToString() unexpected behaviour

查看:346
本文介绍了dynamic.ToString()意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这段代码如何工作:

I'm wondering how does this code work:

dynamic dynaString = 2;
string b = dynaString.ToString();

当此命令不起作用时:

var list = new List<dynamic>();
var liststring = new List<string>();
liststring = list.Select(x => x.ToString()).ToList();

我知道我可以添加 Cast< string> 在Select语句之后,但不能解释该行为。为什么在代码中声明的动态变量上调用 ToString()时,动态元素上的工作与在LINQ中从列表中获取的动态变量上的工作不同。

I know I can add Cast<string> after Select statement but that does not explain that behaviour. Why does ToString() on dynamic element work different when called on dynamic variable declared in code than on dynamic variable taken from list in LINQ.

我研究了 Select 的方法签名,它是:

I've looked into method signature of Select and it's:

我的猜测是,这里的 x 是一个动态变量,因此应该行为就像 dynaString 一样,但事实并非如此。 Intellisense建议我该 x.ToString()返回 string

My guess is that x here is a dynamic variable, so it should behave just like dynaString, but it's not. Intellisense is suggesting me that this x.ToString() returns string:


< img src = https://i.stack.imgur.com/W9lJ8.png alt =在此处输入图片描述>

任何人都可以

我也尝试过以下代码:

var list = new List<dynamic>();
var liststring = new List<string>();
foreach (dynamic a in list)
{
    liststring.Add(a.ToString());
}

它会按预期进行编译,因为 a 在foreach语句中声明为动态。

It compiles as expected, because again the a is declared as dynamic in foreach statement.

推荐答案

根据动态类型文档


动态类型表明使用变量及其成员的引用会绕过编译时类型检查。而是在运行时解决这些操作。

The dynamic type indicates that use of the variable and references to its members bypass compile-time type checking. Instead, these operations are resolved at run time.

在大多数情况下,type dynamic的行为类似于type object。特别是,任何非null表达式都可以转换为动态类型。动态类型与对象的不同之处在于,包含动态类型的表达式的操作不会被编译器解析或检查。

Type dynamic behaves like type object in most circumstances. In particular, any non-null expression can be converted to the dynamic type. The dynamic type differs from object in that operations that contain expressions of type dynamic are not resolved or type checked by the compiler.

没有办法推断

如果省略泛型类型参数,默认情况下将返回 dynamic 类型,即使您调用 ToString()方法也是如此。原因是可以将任何非null表达式分配给 dynamic 。由于 dynamic 是源文件,因此它也是 Select(x => x.ToString())的结果

If you omit generic type parameter it will by default return dynamic type even you call ToString() method. The reason is that any non-null expression can be assigned to dynamic. As dynamic is source, it will be also the result of Select(x => x.ToString()) method call.

另一方面,您可以将 dynamic 对象分配给 string 调用 ToString()时的变量,该变量返回 string 实例。

On the other hand you can assign dynamic object to string variable as you are calling ToString() which returns string instance.

这篇关于dynamic.ToString()意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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