gpt4 book ai didi

c# - 为什么这个 string.Format() 不返回字符串,而是动态的?

转载 作者:可可西里 更新时间:2023-11-01 08:15:28 25 4
gpt4 key购买 nike

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

在 MVC View 中,我使用这样的值:

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

在这里,title1 工作正常。但是 title2 ActionLink 因编译器错误而失败:

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() 有很多重载,但返回类型始终是 string。为什么这里使用var 的变量声明会失败?

最佳答案

好的,所以我们已经从评论和其他答案中知道问题出在 dynamic 中。由于 dynamic在运行时 绑定(bind)的,因此只有在那个时候才完成重载解析和类型验证。

因此:如果至少有一个参数是动态,则重载解析将在运行时完成。

这就是允许这个明显错误的原因:

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

如果没有返回 intstring.Format 重载,它也不会打扰。它稍后会对其进行评估。

关于c# - 为什么这个 string.Format() 不返回字符串,而是动态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35366650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com