为什么没有这样的String.format()返回的字符串,而是动态的? [英] Why doesn't this string.Format() return string, but dynamic?

查看:190
本文介绍了为什么没有这样的String.format()返回的字符串,而是动态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@{
    ViewBag.Username = "Charlie Brown";
    string title1 = string.Format("Welcome {0}", ViewBag.Username);
    var title2 = string.Format("Welcome {0}", ViewBag.Username);
}

在MVC视图我使用的值是这样的:

In the MVC view I use the values like this:

@Html.ActionLink(title1, "Index")
@Html.ActionLink(title2, "Index")

在这里, TITLE1 工作正常。但 TITLE2 ActionLink的失败,一个编译器错误:

Here, the title1 works fine. But the title2 ActionLink failed with a compiler error:

CS1973:'System.Web.Mvc.HtmlHelper'有一个名为StandardHeader没有适用的方法,但似乎有这个名字的扩展方法。扩展方法不能进行动态调度。考虑强制转换动态参数或调用没有扩展方法的语法扩展方法。

CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'StandardHeader' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

的String.format()有相当多的过载,但返回类型总是字符串。为什么使用 VAR 变量声明不能在这里?

string.Format() has quite a few overloads, but the return type is always string. Why does the variable declaration using var fail here?

推荐答案

好了,我们已经从意见和其他答案知道问题是出在动态。由于动态必然的上运行时的,只有在那个时候是重载解析和类型验证完成。

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);

如果没有一个的String.Format 重载返回 INT 它不打扰。它评估了以后。

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

这篇关于为什么没有这样的String.format()返回的字符串,而是动态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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