gpt4 book ai didi

c# - 内联辅助方法如何以及为何在运行时评估类型?

转载 作者:行者123 更新时间:2023-11-30 16:55:50 25 4
gpt4 key购买 nike

如您所知,我们可以在 ASP.NET MVC 中创建两种类型的Helper 方法:

  • 内联辅助方法
  • 外部辅助方法

现在,假设我使用 ViewBag 对象将数据从 Controller 传递到 View 。像那样:

ViewBag.Fruits = new string[] {"Apple", "Orange", "Pear"};

我在 View 中定义了这样的内联辅助方法:

@helper ListArrayItemsInline(string[] items)
{
...
}

这里是一个外部辅助方法,它将字符串数组作为输入:

public static MvcHtmlString ListArrayItemsExternal(this HtmlHelper html, string[] list)
{
...
}

区别是,如果我想使用外部的,我必须将 ViewBag.Fruits 转换为 string[]。是的,一切都在这里。但是,内联的情况并非如此。如我所见,它会在运行时评估类型。

// external one, we must cast 
@Html.ListArrayItemsExternal((string[])ViewBag.Fruits)

// internal one, works just fine
@ListArrayItemsInline(ViewBag.Fruits)

你能解释一下内联辅助方法如何以及为什么在运行时评估类型吗?

最佳答案

区别仅在于用于调用帮助器的语法:ListArrayItemsInline 是普通方法,而ListArrayItemsExternal 是扩展方法.如果您尝试在不强制转换参数的情况下将 ListArrayItemsExternal 作为扩展方法调用,则编译器会给出此错误消息:

CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'ListArrayItemsExternal' 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.

错误消息建议了两个解决错误的选项:

选项 1. 转换动态参数:

@Html.ListArrayItemsExternal((string[])ViewBag.Fruits) 

选项 2。使用普通方法语法调用 ListArrayItemsExternal,在这种情况下您不必转换动态参数:

MyHelpers.ListArrayItemsExternal(Html, ViewBag.Fruits)

第二个选项表明类型可以在运行时为外部辅助方法解析。您只需要使用正确的语法即可。

至于为什么扩展方法不能被动态调度,查看this answer by Eric Lippert .

关于c# - 内联辅助方法如何以及为何在运行时评估类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28928307/

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