2016-06-13 80 views
-5

我想访问在类中定义的全局变量。我无法访问我的覆盖函数内的变量。我该怎么办?下面 是代码:我将如何访问我的类中的公共变量

public partial class VR: System.Web.UI.Page 
    { 
     public SqlConnection SQLCONN; 
     public string headervalue = ""; 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     }    

    // code............... 



    public class ITextEvents : PdfPageEventHelper 
    { 

     // code.... 



     public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) 
     { 

      string value = ""; 
      // code..................................... 
      headervalue  //error unable to access it here 

     } 

      protected void btnExport_Click(object sender, EventArgs e) 
    { 
     headervalue = "abcc"; 
     CreatePDF(); 
    } 

我试图访问headervalue公共覆盖空洞内的OnEndPage method.I我能够访问headervalue到btnExport点击方法

+4

您能否只粘贴相关代码? –

+2

'headervalue'被声明**其中**?你不能在类之外声明它,因为你的粘贴代码显示 –

+0

看起来你试图通过将它放在类之外来定义*“全局变量”*。你不能在C#中做到这一点,它是无效的语法。对此的解决方案将取决于您认为“全局变量”是什么? – Liam

回答

1

变量只能在类中声明。

因此,为了使用它,你都必须做:

public class ITextEvents : PdfPageEventHelper 
{ 
    public static string headervalue = ""; 

    public override void OnEndPage(PdfWriter writer, Document document) 
    { 
     [..your implementation..] 
    } 
} 

如果你想多个类之间的分享,您需要使用容器像SimpleIOC。

我不知道它是否会帮助你。

+0

我想访问headervalue成两个方法一个是OnEndPage和btnExport点击。我将分配一些值到btnExport点击一个将访问这个值到公共覆盖方法()。我可以访问headervalue到btnExport点击方法 – ROY

+0

所以只需设置'headervalue'就像我在我的答案中所做的那样。简单的解决方案不是最好的。 –

+0

但是,我将如何从btnExport方法分配特定值给headervalue – ROY

相关问题