Why doesn't this string.Format() return string, but dynamic?

后端 未结 3 1301
野性不改
野性不改 2020-12-31 10:12
@{
    ViewBag.Username = \"Charlie Brown\";
    string title1 = string.Format(\"Welcome {0}\", ViewBag.Username);
    var title2 = string.Format(\"Welcome {0}\", Vi         


        
相关标签:
3条回答
  • 2020-12-31 10:14

    It's the view bag which is dynamic.

    If you use actual username (instead of ViewBag.UserName)it would work. Or cast (string)ViewBag.Username into string.

    0 讨论(0)
  • 2020-12-31 10:17

    Okay, so we already know from comments and other answers that the problem is in dynamic. Since dynamic is bound on runtime, only at that time is the overload resolution and type validating is done.

    So: if at least one of the parameters is dynamic, the overload resolution is done at runtime.

    That is why this obvious mistake is allowed:

    dynamic x = "";
    int i = string.Format("{0}", x);
    

    It doesn't bother if there isn't a string.Format overload that returns an int. It evaluates that later on.

    0 讨论(0)
  • 2020-12-31 10:23

    The error message is telling you exactly what's wrong here:

    Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

    title2 is of type dynamic. You need to cast it to string, since you know that's what it is.

    0 讨论(0)
提交回复
热议问题