无法访问派生类中的公共变量

时间:2014-11-05 18:35:04

标签: c#

我正在尝试使用指定的字体打印变量,但字符串为null,因此输出中没有任何内容可见。请仔细阅读代码并帮我找到错误

 class BasicClass
{
    public string str;
    public Font fnt;
}
class BasicMethod:BasicClass
{
    public void changevalues(string newstr,Font newfnt)
    {
        str = newstr;
        fnt = newfnt;
    }
}
class PrintClass:BasicClass
{
    public void print()
    {

        PrintDialog pd = new PrintDialog();
        PrintDocument pdoc = new PrintDocument();
        PrinterSettings ps = new PrinterSettings();
        PaperSize psize = new PaperSize();
        pdoc.DefaultPageSettings.Landscape = true;
        pd.Document = pdoc;
        pd.Document.DefaultPageSettings.PaperSize = psize;
        pdoc.PrintPage += new PrintPageEventHandler(pdoc_PrintPage);

        DialogResult result = pd.ShowDialog();
        if (result == DialogResult.OK)
        {
            PrintPreviewDialog ppd = new PrintPreviewDialog();
            ppd.Document = pdoc;
            ppd.PrintPreviewControl.Zoom = 1.5;
            ((Form)ppd).WindowState = FormWindowState.Maximized;
            DialogResult ppdResult = ppd.ShowDialog();

        }
    }
    void pdoc_PrintPage(object sender, PrintPageEventArgs e)
    {
        Graphics g = e.Graphics;
        //string str1 = "XYZ";
        //Font fnt1 = new Font("Arial", 12.5f);            
        g.DrawString(str, fnt, new SolidBrush(Color.Black), 10, 10);

    }

}

按钮点击事件

 private void button1_Click(object sender, EventArgs e)
    {
        BasicMethod bm = new BasicMethod();
        PrintClass pc = new PrintClass();
        Font ft = new System.Drawing.Font("Arial", 12.5f);
        bm.changevalues("Hello", ft);
        pc.print();

    }

我需要输出Hello

1 个答案:

答案 0 :(得分:3)

您正在尝试使用完全不同的对象中设置所需的值。

解决此问题的一种方法:

更改PrintClass,使其继承BasicMethod班级,而不是BasicClass

class PrintClass : BasicMethod

然后更改您的点击处理程序:

private void button1_Click(object sender, EventArgs e)
{
    PrintClass pc = new PrintClass();
    Font ft = new System.Drawing.Font("Arial", 12.5f);
    pc.changevalues("Hello", ft);
    pc.print();
}