问题描述:
有一个用户控件的基类,有许多公用属性.派生了30个类希望在实例化时初始化基类的属性
如何做更好?
这样做行吗?
public class Base:UserControl
{
private string a;
private string b;
.
.
.
public string a1
{ get{return a;} set{a=value;}
}
public string b1
{ get{return b;} set{b=value;}
}
.
.
.
public Base(string aa,string bb....)
{
a1=aa;
b1=bb;
}
}public class child1:Base
{
public child1(string aa,string bb....):base(aa,bb...)
}public class main
{
string aa,bb....
child1=new child1(aa,bb....) //还有没有更好的,太烦了嘛.
child2=new child2(aa,bb....)
.
.
.
}
有一个用户控件的基类,有许多公用属性.派生了30个类希望在实例化时初始化基类的属性
如何做更好?
这样做行吗?
public class Base:UserControl
{
private string a;
private string b;
.
.
.
public string a1
{ get{return a;} set{a=value;}
}
public string b1
{ get{return b;} set{b=value;}
}
.
.
.
public Base(string aa,string bb....)
{
a1=aa;
b1=bb;
}
}public class child1:Base
{
public child1(string aa,string bb....):base(aa,bb...)
}public class main
{
string aa,bb....
child1=new child1(aa,bb....) //还有没有更好的,太烦了嘛.
child2=new child2(aa,bb....)
.
.
.
}
构造函数的某些参数给移除了.改成了给属性附值.
那怎样实例化子类对象呢!?Base childA=new child1() 行吗!? 能否给个小例子.
childA.属性A = 值A;
childA.属性B = 值B;
childA.属性C = 值C;
......
{
public string SomeProp
{
//....
} public baseC()
{
SomeProp = "abc"; //if const value
} public baseC(string s)
{
SomeProp = s;
}
}public class ChildC : baseC
{
public ChildC()
{
//after this, SomeProp will have "abc";
} public ChildC():base("def")
{
//after this, SomeProp will have "def";
}
}
private string property1 = "abc";
public string Property1
{
get
{
return this.property1;
}
}2. 如果是动态初始化,也就是说创建每个类实例的时候都想让属性有不同的初始值,那么可以在构造函数中加上传进来的初始值,也可以写个函数来初始化所有需要初始化的属性:
private string property1 = "";
private string property2 = "";public string Property1
{
get
{
return this.property1;
}
}
public string Property2
{
get
{
return this.property2;
}
}构造函数法:
public BaseClass(string property1, string property2)
{
this.property1 = property1;
this.property2 = property2;
}
BaseClass cls = new BaseClass("a", "b");用函数初始化:
public BaseClass()
{
}
public void InitialValue(string property1, string property2)
{
this.property1 = property1;
this.property2 = property2;
}
BaseClass cls = new BaseClass();
cls.InitialValue("a", "b");