如何从泛型类访问父类中的方法
本文关键字:方法 父类 访问 泛型类 | 更新日期: 2023-09-27 18:08:48
我想这样做。
为了使用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助手可用,我绝对不想有重复的代码。但是写这个泛型类的正确方法是什么呢?
创建一个包含AddClass
和Attributes
的接口,将其应用到Alert
类并将其添加为类型约束(IHelper<T> where T : IYourInterface
)