dynamic.ToString() unexpected behaviour

家住魔仙堡 提交于 2020-01-03 21:04:23

问题


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. 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.

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

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:

Anyone got experience with dynamics in C# and can explain me that?


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.


回答1:


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. The dynamic type differs from object in that operations that contain expressions of type dynamic are not resolved or type checked by the compiler.

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. 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.

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



来源:https://stackoverflow.com/questions/57270215/dynamic-tostring-unexpected-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!