【问题标题】:Using interface on ASP.NET MVC html helper在 ASP.NET MVC html helper 上使用接口
【发布时间】:2011-02-03 21:29:46
【问题描述】:

我有以下方法:

public static string UlList(this HtmlHelper helper, List<IEntity> entities, string css)
{
    return "foo";
}

但是当我尝试调用该方法时

<%= Html.UlList(Model.ProfileRequiredFields, css)%>

我明白了:

编译器错误消息:CS1928:“System.Web.Mvc.HtmlHelper”不包含“UlList”的定义和最佳扩展方法重载“System.Web.Mvc.HtmlHelpers.UlList(System.Web.Mvc. HtmlHelper, System.Collections.Generic.List, string)' 有一些无效参数

Model.RequiredFields = new List<ProfileRequiredField>();

public class ProfileRequiredField : IEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
}

编辑 我正在使用 3.5

【问题讨论】:

    标签: c# asp.net-mvc-2


    【解决方案1】:

    由于新的out 关键字,您尝试使用List&lt;IEntity&gt; 作为参数类型仅在.NET 4.0 中有效。

    如果您需要它在较低版本中工作,请尝试以下操作:

    public static string UlList<T>(this HtmlHelper helper, List<T> entities, string css)
        where T : IEntity
    {
        return "foo";
    }
    

    这会将IEntity 替换为通用参数。 .NET 会自动为您解决此问题,因此您不必在代码中添加 &lt;ProfileRequiredField&gt;。

    【讨论】:

    • 好的,所以我不能使用这是 Net 3.5。它实际上不需要是扩展方法。
    • 不,您不能在 3.5 中使用 List&lt;IEntity&gt;。上面的泛型是专门为了使这项工作在 3.5 中工作:)。澄清了答案。
    【解决方案2】:

    请确保您的扩展方法位于 System.Web.Mvc 命名空间中,或将您的命名空间包含在 web.config 文件中定义的命名空间列表中。

    【讨论】:

    • -1 不。编译器已经看到了该方法,否则它不会检测到参数不正确。
    • 扣分有点老套。这是一个完全有效的检查。就你所知,可能已经在不同的命名空间中编写了多个版本的扩展。
    猜你喜欢
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多