这是我想要做的。
要使用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
。然后很难将我的IHelper
和Helper
更改为通用IHelper<T>
和Helper<T>
,以用于我的其他自定义帮助程序,例如DropDownList
和CheckBoxGroup
由于AddClass
和Attributes
方法应该适用于所有其他Html帮助程序,因此我绝对不希望拥有重复的代码。但是编写这个泛型类的正确方法是什么?
答案 0 :(得分:1)
创建包含AddClass
和Attributes
的界面,将其应用于Alert
类,并将其添加为类型约束(IHelper<T> where T : IYourInterface
)。