[英]How to set value for a base class from derived class in c# wpf
public class Baseclass
{
private int mTotal = 0;
private int mID = 0;
public int Total
{
get { return mTotal; }
set { mTotal = value;}
}
public int ID
{
get { return mID; }
set { mID = value;}
}
}
public class Derivedclass : Baseclass
{
private int mX = 0;
private int mY = 0;
public int X
{
get { return mX; }
set
{
mX = value;
Total = Total + mX;
}
}
public int Y
{
get { return mY; }
set
{
mY = value;
Total = Total + mY;
}
}
}
public partial class Test : Page
{
Baseclass B = new Baseclass();
Derivedclass D = new Derivedclass();
public Test()
{
Calculate();
}
public void Calculate()
{
for(int i =1; i <5 ;i++)
{
B.ID = i;
for (int j = 0; j < 5; j++)
{
D.X = j;
D.Y = j;
}
MessageBox.Show("ID " + B.ID + " Total Sum" + B.Total);
B.Total = 0;
}
}
// Out put should be
// ID 1 Total Sum 16
// ID 2 Total Sum 16
// ID 3 Total Sum 16
// ID 4 Total Sum 16
}
这里我有两个类,Baseclass和derivedclass。 我想找出派生类中x和y属性的总和,并将总和设置为基类的Total属性而我想要的应该是这样的
// ID 1 Total Sum 16
// ID 2 Total Sum 16
// ID 3 Total Sum 16
如果要引用任何继承的成员,您可以只使用属性名称,如上所示。 如果存在名称冲突,或者您希望更清楚,可以使用base关键字,如下所示:
base.Total = 15;
这是关于base关键字的MSDN文章: http : //msdn.microsoft.com/en-us/library/hfw7t1ce.aspx
不过,看起来你对继承的想法有点困惑。 Baseclass的实例与Derivedclass的实例没有任何关系,反之亦然,因为它们是完全独立的对象,彼此缺少引用。 继承控制类具有的成员(字段,属性和方法),并允许派生类重用其父代码,同时将其功能扩展到更具体的用例。 简而言之,你的B和D对象永远不会彼此交谈,而这首先不是继承的重点。
因此,如果没有无用的B对象,您的Calculate方法应如下所示:
public void Calculate()
{
for(int i = 1; i < 5; i++)
{
D.ID = i;
for (int j = 0; j < 5; j++)
{
D.X = j;
D.Y = j;
}
MessageBox.Show("ID " + D.ID + " Total Sum" + D.Total);
D.Total = 0;
}
}
此版本的Calculate()将显示以下内容:
ID 1 Total Sum 20
ID 2 Total Sum 20
ID 3 Total Sum 20
ID 4 Total Sum 20
您不需要为基类和派生类创建单独的实例。 派生类中将包含基类属性。
您的Test类应如下所示
public partial class Test : Page
{
Derivedclass D = new Derivedclass();
public Test()
{
Calculate();
}
public void Calculate()
{
for(int i =1; i <5 ;i++)
{
D.ID = i;
for (int j = 0; j < 5; j++)
{
D.X = j;
D.Y = j;
}
MessageBox.Show("ID " + D.ID + " Total Sum" + D.Total);
D.Total = 0;
}
}
// Out put should be
// ID 1 Total Sum 16
// ID 2 Total Sum 16
// ID 3 Total Sum 16
// ID 4 Total Sum 16
}
你的基类可以有一个虚方法。 而不是财产
class Baseclass
{
public virtual int GetTotal(){return 0;} // or throw new NotImplementedException();
}
public class Derivedclass:Baseclass
{
int x = 2;
int y = 3;
public override int GetTotal()
{
return x + y;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.