简体   繁体   中英

Why does C# infer this type as dynamic?

I have the following code.

public static void GuessTheType()
{
    dynamic hasValue = true;
    dynamic value = "true";

    var whatami1 = hasValue ? (string)value : null;
    var whatami2 = hasValue ? bool.Parse(value) : true;
    var whatami3 = hasValue ? (bool)bool.Parse(value) : true;
}

The type inferred by the compiler for whatami1 is string .
The type inferred by the compiler for whatami2 is dynamic .
The type inferred by the compiler for whatami3 is bool .

Why is the second type not bool ?

为了扩展PetSerAl的注释,它解释了为什么它被视为动态的,你可以通过将值转换为字符串来避免将bool.Parse的调用视为动态:

var whatami2 = hasValue ? bool.Parse((string)value) : true;

Casting is our assertion (to the compiler) that an object really is something else - for example:

var whatami1 = hasValue ? (string)value : null;
var whatami3 = hasValue ? (bool)bool.Parse(value) : true;

Finally, parsing is interpreting a value from a form with no intrinsic relationship - ie there is no direct relationship between a dynamic ( ie value) and var (ie whatami2), but we can parse:

var whatami2 = hasValue ? bool.Parse(value) : true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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