2014-11-05 90 views
-3

我想用指定的字体打印一个变量,但字符串为空,因此在输出中没有任何内容可见。请通过代码,并帮助我找到错误无法访问派生类中的公共变量

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

恭喜回答!你应该去你以前的问题,并添加一个答案链接到这个页面上的答案。 – 2014-11-05 19:42:37

回答

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(); 
}