2014-11-05 97 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(); 
}