我一直在努力 ( http://tinyurl.com/m4hzjb ) 使用这个 Fluent API 来实例化 ASP.NET 控件,并且觉得我现在有一些看起来运行良好的东西。我正在寻找一些反馈和意见......好的,坏的或冷漠的。你会觉得这有用吗?您预见到的任何技术问题?改进空间?
这是创建标准 TextBox 控件的一个非常基本的用法示例。仅实现了两个属性/方法,但可以轻松扩展 API 以支持控件的完整属性功能集。
用法
Factory.TextBox()
.ID("TextBox1")
.Text("testing")
.RenderTo(this.form1);
// The above TextBox Builder is functionally same as:
TextBox textbox = new TextBox();
textbox.ID = "TextBox1";
textbox.Text = "testing";
this.form1.Controls.Add(textbox);
// Or:
this.form1.Controls.Add(new TextBox {
ID = "TextBox1",
Text = "testing"
});
这是完整的 ControlBuilder 类。
建造者
public partial class Factory
{
public static TextBoxBuilder TextBox()
{
return new TextBoxBuilder(new TextBox());
}
}
public abstract class ControlBuilder<TControl, TBuilder>
where TControl : Control
where TBuilder : ControlBuilder<TControl, TBuilder>
{
public ControlBuilder(TControl control)
{
this.control = control;
}
private TControl control;
public virtual TControl Control
{
get
{
return this.control;
}
}
public virtual void RenderTo(Control control)
{
control.Controls.Add(this.Control);
}
public TBuilder ID(string id)
{
this.Control.ID = id;
return this as TBuilder;
}
}
public abstract class TextBoxBuilder<TTextBox, TBuilder> : ControlBuilder<TTextBox, TBuilder>
where TTextBox : TextBox
where TBuilder : TextBoxBuilder<TTextBox, TBuilder>
{
public TextBoxBuilder(TTextBox control) : base(control) { }
public TBuilder Text(string text)
{
this.Control.Text = text;
return this as TBuilder;
}
}
public class TextBoxBuilder : TextBoxBuilder<TextBox, TextBoxBuilder>
{
public TextBoxBuilder(TextBox control) : base (control) { }
}