private System.Windows.Forms.Label tmp; 
private static void AA()
{
this.tmp.Text = "x";//这样不行;
}
private void BB()
{
this.tmp.Text = "x";//这样可以;
}怎么样实现在静态方法里访问象在非动态方法里使用this访问静态变量。
谢谢。

解决方案 »

  1.   

    test.cs(9,9): error CS0026: Keyword 'this' is not valid in a static property,
            static method, or static field initializer
    静态方法里不允许用this
    既然要访问静态变量,何必用this,直接访问不就行了吗?
      

  2.   

    在静态方法里不可能用this访问静态变量。this表示的就是当前对象,而静态方法执行的时候是没有对象的,因此肯定达不到lz想要的效果。如果不限制用this,那么单例模式说不定可行
      

  3.   

    有一种解决方案是在你的静态方法中包含一个该类型的参数。
    如下
    public class TestClass
    {
         private System.Windows.Forms.Label tmp; 
        private static void AA(TestClass obj)
        {
            obj.tmp.Text = "x";
         }
    }
      

  4.   

    我知道通过以下两种方式可以实现:
    一、
    private static void best(Form1 obj)
    {
    obj.label1.Text = "";
    }
    二、
    private static void best(System.Windows.Forms.Label label1)
    {
    label1.Text = "";
    }
    但是当方法里面不允许委拖时,应该怎么传进去?如:private static void Test(object sender, System.Timers.ElapsedEventArgs e)
    {
      label1.Text = "";//这里不允许这样使用。
    }
      

  5.   

    那请问你sender里是什么呢?
    是什么控件促发了这个Test事件呢?
    如果说sender是窗体Form,那么就这样。private static void Test(object sender, System.Timers.ElapsedEventArgs e)
    {
      MyForm frm = (MyForm)sender;
      frm.label1.Text = "";
    }
    如果说一个按钮什么的private static void Test(object sender, System.Timers.ElapsedEventArgs e)
    {
      MyForm frm = (MyForm)sender.Parent;
      frm.label1.Text = "";
    }不过通常将sender取得的对象实例化成一个普通的Form,然后用FindControl方法去查找你需要的控件。
      

  6.   

    不行哦,导致点击按钮后无法运行。
    public class Form1 : System.Windows.Forms.Form
    {
    ……
    private void button1_Click(object sender, System.EventArgs e)
    {

    System.Timers.Timer timer1 = new System.Timers.Timer();
    timer1.Elapsed += new System.Timers.ElapsedEventHandler(Test);
    timer1.Interval = 10000;
    timer1.Enabled = true;
    timer1.Start();
    }
    private static void Test(object sender, System.Timers.ElapsedEventArgs e)
    {
      Form1 frm = (Form1)sender;
      MessageBox.Show(frm.label1.Text);
    }
    ……
    }
      

  7.   

    不好意思,我搞错了哦,
    因为开始写个static,后来忘记取消了。