如何从泛型类访问父类中的方法?

时间:2014-06-16 20:38:05

标签: c# html-helper fluent

这是我想要做的。

要使用Fluent API创建自定义Html Helper,我创建了这个:

public interface IHelper:IHtmlString
{
    IHelper AddClass(string className);
    IHelper Attributes(object htmlAttributes);
}

public class Helper : IHelper
{
    private readonly Alert _parent;

    public Helper(Alert parent)
    {
        _parent = parent;
    }

    public string ToHtmlString()
    {
        return ToString();
    }

    public IHelper AddClass(string className)
    {
        return _parent.AddClass(className);
    }

    public IHelper Attributes(object htmlAttributes)
    {
        return _parent.Attributes(htmlAttributes);
    }
    public override string ToString()
    {
        return _parent.ToString();
    }
}

Alert类:

public interface IAlert : IHelper
{
    IHelper HideCloseButton(bool hideCloseButton);
    IHelper Success();
    IHelper Warning();
}

public class Alert : IAlert
{
    private readonly string _text;
    private AlertStyle _style;
    private  bool _hideCloseButton;
    private ICollection<string> _cssClass;
    private  object _htmlAttributes;

    public Alert(string text, AlertStyle style, bool hideCloseButton = false, object htmlAttributes = null)
    {
        _text = text;
        _style = style;
        _hideCloseButton = hideCloseButton;
        _htmlAttributes = htmlAttributes;
    }
    public override string ToString()
    {
        return "";
    }

    public string ToHtmlString()
    {
        return RenderAlert();
    }
    // private method RenderAlert() is omitted here.

    public IHelper AddClass(string className)
    {
        if (_cssClass == null) _cssClass = new List<string>();
        _cssClass.Add(className);
        return new Helper(this);
    }

    public IHelper Attributes(object htmlAttributes)
    {
        _htmlAttributes = htmlAttributes;
        return new Helper(this);
    }

    public IHelper HideCloseButton(bool hideCloseButton)
    {
        _hideCloseButton = hideCloseButton;
        return new Helper(this);
    }

    public IHelper Success()
    {
        _style = AlertStyle.Success;
        return new Helper(this);
    }

    public IHelper Warning()
    {
        _style = AlertStyle.Warning;
        return new Helper(this);
    }
}

问题是我的Helper类的构造函数直接访问Alert。然后很难将我的IHelperHelper更改为通用IHelper<T>Helper<T>,以用于我的其他自定义帮助程序,例如DropDownListCheckBoxGroup

由于AddClassAttributes方法应该适用于所有其他Html帮助程序,因此我绝对不希望拥有重复的代码。但是编写这个泛型类的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

创建包含AddClassAttributes的界面,将其应用于Alert类,并将其添加为类型约束(IHelper<T> where T : IYourInterface)。