简体   繁体   English

dynamic.ToString()意外行为

[英]dynamic.ToString() unexpected behaviour

I'm wondering how does this code work: 我想知道这段代码是如何工作的:

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

When this one is not working: 当这个不工作时:

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

I know I can add Cast<string> after Select statement but that does not explain that behaviour. 我知道我可以在Select语句之后添加Cast<string> ,但这并不能解释这种行为。 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. 为什么动态元素上的ToString()在代码中声明的动态变量上调用时不同于在LINQ中从列表中获取的动态变量上调用。

I've looked into method signature of Select and it's: 我查看了Select方法签名,它是:

在此输入图像描述

My guess is that x here is a dynamic variable, so it should behave just like dynaString , but it's not. 我的猜测是x这里是一个动态变量,所以它应该像dynaString一样,但事实并非如此。 Intellisense is suggesting me that this x.ToString() returns string : Intellisense建议我这个x.ToString()返回string

在此输入图像描述 在此输入图像描述

Anyone got experience with dynamics in C# and can explain me that? 任何人都有C#的动态经验,可以解释一下吗?


I've also tried this code: 我也试过这段代码:

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

It compiles as expected, because again the a is declared as dynamic in foreach statement. 它按预期编译,因为a在foreach语句中再次声明为动态。

According to dynamic type docs : 根据动态类型文档

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 behaves like type object in most circumstances. 在大多数情况下,类型动态类似于类型对象。 In particular, any non-null expression can be converted to the dynamic type. 特别是,任何非null表达式都可以转换为动态类型。 The dynamic type differs from object in that operations that contain expressions of type dynamic are not resolved or type checked by the compiler. 动态类型与object的不同之处在于,包含dynamic类型表达式的操作未被编译器解析或类型检查。

There is no way to infer type from usage in case type checking and/or resolution is bypassed at compile-time. 在编译时绕过案例类型检查和/或解析时,无法从使用情况推断出类型。

If you omit generic type parameter it will by default return dynamic type even you call ToString() method. 如果省略泛型类型参数,即使调用ToString()方法,它也会默认返回dynamic类型。 The reason is that any non-null expression can be assigned to dynamic . 原因是任何非null表达式都可以分配给dynamic As dynamic is source, it will be also the result of Select(x => x.ToString()) method call. 由于dynamic是源,它也将是Select(x => x.ToString())方法调用的结果。

On the other hand you can assign dynamic object to string variable as you are calling ToString() which returns string instance. 另一方面,当您调用返回string实例的ToString() ,您可以将dynamic对象分配给string变量。

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

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