Question regarding common class
I have following two classes:
public class A : System.Web.UI.WebControls.Button
{
public virtual string X
{
get
{
object obj = ViewState["X"];
if (obj != null) return (string)obj;
return null;
}
set
{
ViewState["X"] = value;
}
}
protected override void OnLoad(EventArgs e)
{
X=2;
}
}
and
public class B : System.Web.UI.WebControls.TextBox {
public virtual string X
{
get
{
object obj = ViewState["X"];
if (obj != null) return (string)obj;
return null;
}
set
{
ViewState["X"] = value;
开发者_开发知识库 }
}
protected override void OnLoad(EventArgs e)
{
X=2;
}
}
As you must be seeing the class A and B have exactly the same code , my question is how can I make a common class for it and use these two classes.
The replacement for inheritance is composition. Define a new class and insert invocations of it's methods in A and B. In this example it seems too complicated, but you will avoid code duplication if you decide to replace ViewState["X"]
class C {
public virtual string X
{
get
{
return ViewState["X"];
}
set
{
ViewState["X"] = value;
}
}
public SetX()
{
X=2;
}
}
Extension methods is a good alternative too.
精彩评论