我想在派生类中使用基类属性。另外,我必须从外面传递属性值。我可以想到以下两种方法:
方法1:
class Mydata
{
}
class Converter1:Converter
{
void Converter1(Mydata data1)
{
data = data1;
}
public void Convert()
{
// USING "data" here
}
}
class Converter2 : Converter
{
void Converter2(Mydata data2)
{
data = data1;
}
public void Convert()
{
//USING "data" here
}
}
创建对象时,我可以创建如下:
Mydata data1 =new Mydata()
Mydata data2 =new Mydata()
Coverter cObj= Converter1(data1 )
cObj.Convert()
Coverter cObj1= Converter2(data2 )
cObj1.Convert();
方法2:
class Mydata
{
}
class Covnerter1:Converter
{
public void Convert()
{
// USING "data" here
}
}
class Converter2 : Converter
{
public void Convert()
{
// USING "data" here
}
}
创建对象时,我可以像下面这样创建对象,并在基类中设置属性值。
Mydata data1 =new Mydata()
Mydata data2 =new Mydata()
Coverter cObj= Converter1()
cObj.data = data1;
cObj.Convert()
Coverter cObj1= Converter2()
cObj1.data =data2
cObj1.Convert()
哪种方法更好?还是其他更好的方法?
答案 0 :(得分:1)
忽略"转换器"奇异...
更好地分享更多代码和封装数据":通常,如果需要设置基类的属性,可以通过基类构造函数来完成:
class Base
{
public MyData { get; private set; }
public Base(MyData data)
{
MyData = data;
}
}
class Derived : Base
{
public Derived(MyData data):base(data)
{}
// Methods that use MyData here...
}