gpt4 book ai didi

c# - 为什么在 MVC4 Razor View 中找不到扩展方法?

转载 作者:IT王子 更新时间:2023-10-29 04:30:16 26 4
gpt4 key购买 nike

给定以下字符串扩展方法

namespace JHS.ExtensionMethods
{
public static class StringExtensions
{
public static string ToUSAPhone(this String str)
{
return String.Format("{0:(###) ###-####}", Double.Parse(str));
}
}
}

@using 语句已添加到 MVC4 Razor View

@using JHS.ExtensionMethods;

和下面的字符串值调用扩展方法

@Model.producer.phone.ToUSAPhone()

导致以下错误

'string' does not contain a definition for 'ToUSAPhone'

我还尝试将命名空间放在/Views 文件夹的 web.config 中,但收到同样的错误。

<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="JHS.ExtensionMethods"/>
</namespaces>
</pages>

我已经通过将相同的调用放入 C# 类中来验证扩展方法是否有效

string test=producer.phone.ToUSAPhone();

似乎对扩展方法的引用在 MVC4 Razor View 中不可用,但我不明白为什么?

最佳答案

如果您尝试对其使用扩展方法的类型实际上是一个动态,就会发生这种情况。检查异常是否由 CSharp RuntimeBinder 生成。如果是这样,您可以将该方法用作普通方法或花园静态方法:

@StringExtensions.ToUSAPhone(Model.producer.phone)

或者您可以将值转换为字符串:

@(((string)Model.producer.phone).ToUSAPhone())

According to Eric Lippert (以前的 MSFT):

The reason behind the fact that dynamics do not support extension types is because in regular, non-dynamic code extension methods work by doing a full search of all the classes known to the compiler for a static class that has an extension method that match. The search goes in order based on the namespace nesting and available "using" directives in each namespace.

That means that in order to get a dynamic extension method invocation resolved correctly, somehow the DLR has to know at runtime what all the namespace nestings and "using" directives were in your source code. There is no mechanism handy for encoding all that information into the call site.

关于c# - 为什么在 MVC4 Razor View 中找不到扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19255688/

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