Passing interface as a parameter to an extension method

给你一囗甜甜゛ 提交于 2019-12-04 11:33:31

Ahh... try:

 public static string RSSRepeater<T>(this HtmlHelper html, IEnumerable<T> rss)
     where T : IRSSable
 {
     ...
 }

This then should allow you to pass any sequence of things that implement IRSSable - and the generic type inference should mean you don't need to specify the T (as Issue) yourself - the compiler will handle it.

By the way - avoid concatenation here; StringBuilder is preferable:

    StringBuilder result = new StringBuilder();

    foreach (IRSSable item in rss)
    {
        result.Append("<item>").Append(item.GetRSSItem().InnerXml).Append("</item>");
    }

    return result.ToString();
Jon Skeet

You're running into generic variance issues. Just because something implements IEnumerable<Issue> doesn't mean it implements IEnumerable<IRssable>. (It will in C# 4, but I'm assuming you're not using that :)

You could make your extension method take just IEnumerable and call IEnumerable.Cast<IRssable> on it though - that's probably the simplest approach.

EDIT: Marc's suggestion is probably the better one, but I'll leave this answer here as it explains what's going on rather than just the fix :)

Try this:

<%=Html.RSSRepeater(ViewData.Model.GetIssues(null, null, "").Cast<IRSSable>()) %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!