对静态感到困惑 [英] Confused about static

查看:63
本文介绍了对静态感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#程序。我正在观看一个目录,要求更改xml文件,当文件发生变化时,我想准备好xml并更新一个富文本框。

当我指定文件时,一切正常。它读取它并填充RTB罚款。但是当我添加代码以尝试在文件更改时自动执行时我得到错误



错误1非静态字段需要对象引用,方法,或属性'xml_reader.Form1.readXML(string)'



我已经阅读了几个这方面的例子,但我仍然没有得到它。



如果它应该触发

I have a C# program. I'm watching a directory for changes to an xml file, and when the file changes I want to ready the xml and update a rich textbox.
It all works when I specify the file. It reads it and populates the RTB fine. But when I add code to try to do it automatically when the files changes I get the error

Error 1 An object reference is required for the non-static field, method, or property 'xml_reader.Form1.readXML(string)'

I've read several examples on this but I still don't get it.

this fires when it should

private static void OnChanged(object source, FileSystemEventArgs e)
 {
     // Specify what is done when a file is changed, created, or deleted.
     string path = e.FullPath;
     Console.WriteLine("File: " + path + " " + e.ChangeType);
    readXML(path);
 }





我想打电话



I want to call

private void readXML(string Filename)
{
    int linenumbers = 0;
    string stringvalue;
    string stringname;
    String title = "POS           PILOT                 LAPS    ELAPSED      SEED         FAST LAP \n";
    richTextBox1.Text = title;
    XmlTextReader reader = new XmlTextReader(Filename);
    while (reader.Read())
    {
        switch (reader.NodeType)
        {
            case XmlNodeType.Element: // The node is an element.
                if (reader.Name == "Driver")
                {

                    while (reader.MoveToNextAttribute()) // Read the attributes.
                    {
                        stringvalue = reader.Value;
                        stringname = reader.Name;
                        if (stringname == "position")
                        {
                            richTextBox1.Text += (" " + stringvalue + "\t");
                        }
                        if (stringname == "name")
                        {
                            string longname = stringvalue;
                            longname = longname.PadRight(30);
                            int namelength = longname.Length;
                            Console.WriteLine(longname + namelength);
                            richTextBox1.Text += (longname);
                        }
                        if (stringname == "laps")
                        {
                            if (stringvalue == " ")
                                stringvalue = "0";
                            richTextBox1.Text += ("  " + stringvalue + "\t\t");
                        }
                        if (stringname == "seed")
                        {
                            if (stringvalue == " ")
                                stringvalue = "0.000";
                            richTextBox1.Text += (stringvalue + "\t\t");
                        }
                        if (stringname == "elapsedTime")
                        {
                            if (stringvalue == " ")
                                stringvalue = "0.000";
                            richTextBox1.Text += (" " + stringvalue + "\t\t");
                        }
                        if (stringname == "fastLap")
                        {
                            if (stringvalue == " ")
                                stringvalue = "0.000";
                            stringvalue = stringvalue.PadRight(8);
                            richTextBox1.Text += (" " + stringvalue + Environment.NewLine);
                            linenumbers++;
                        }
                    }
                }
                break;
            case XmlNodeType.Text: //Display the text in each element.
                break;
            case XmlNodeType.EndElement: //Display the end of the element.
                break;
        }
    }
    reader.Close();
    colorTextbox(linenumbers);
}







如果我更改功能以便 static void readXML(string Filename)

然后我在richtextbox1上出错。



最简单的修复方法是什么?

先谢谢。



我尝试过:



使被调用的例程变为静态。




If I change the function so that it is "static void readXML(string Filename)"
then I get errors on richtextbox1.

What is the easiest way to fix it?
Thanks in advance.

What I have tried:

making the called routine static.

推荐答案

如果你只是不需要this,那么方法应该是静态的,这是对实例的引用一些班级。这个this是一个传递给所有实例方法的隐式方法。 (这样,实例方法是静态方法的反义词。)您只能在某个实例上调用实例方法( instanceName.MethodName(/ * ... * / ))并且您只能在类型( TypeName.MethodName(/ * ... * / ))上调用静态方法,以便该实例成为对传递给实例的实例的引用实例方法。



您可以通过this访问所有类型的成员,因此,从静态方法只能访问静态成员。在实践中,当你有与其他成员无关的方法时,必须使用静态方法,例如一些仅使用参数操作的数学计算。



更多细节,请查看我过去的答案:

在c#中输入类型

C#windows基于这个关键词及其在应用程序中的用途

是什么让静态方法可以访问?



使用静态方法作为一些事件处理程序是可能的,但它是极不可能变得有用。这解释了Matt T Heffron对问题的评论。



-SA
A method should be static if you simply don't need "this", which is the reference to the instance of some class. This "this" is an implicit method which is passed to all instance methods. (This way, "instance method" is antonym to "static method".) You only can call an instance method on some instance (instanceName.MethodName(/* … */)) and you can only call static method on the type (TypeName.MethodName(/* … */)), so that instance becomes the reference to the instance passed to an instance method.

You can access all type members through "this", and, therefore, from a static method you can only access static member. Using static methods, in practice, is a must when you have methods unrelated to other members, such as some mathematical calculations only operating with parameters.

For some more detail, please see my past answers:
Type casting in c#,
C# windows base this key word related and its uses in the application,
What makes static methods accessible?.

Using a static method as some event handler is possible, but it is extremely unlikely to turn out useful. That explains the comment to the question by Matt T Heffron.

—SA


此外以上关于使OnChanged方法不是静态的评论,你的代码还有其他一些问题。其中最重要的是滥用字符串连接!你应该使用 StringBuilder类(System.Text) [ ^ ]:

In addition to my comment above about making the OnChanged method not be static, there are other things very wrong with your code. Not the least of which is the abuse of string concatenation! You should use StringBuilder Class (System.Text)[^]:
private void readXML(string Filename)
{
  int linenumbers = 0;
  string stringvalue;
  const string title = "POS           PILOT                 LAPS    ELAPSED      SEED         FAST LAP \n";
  StringBuilder builder = new StringBuilder(title, 1024); // 1k is a fair starting "guess" ;-)
  using (XmlTextReader reader = new XmlTextReader(Filename))
  {
    // The using statement ensures that reader is Closed when done.
    while (reader.Read())
    {
      switch (reader.NodeType)
      {
      case XmlNodeType.Element: // The node is an element.
        if (reader.Name == "Driver")
        {
          while (reader.MoveToNextAttribute()) // Read the attributes.
          {
            stringvalue = reader.Value;
            switch (reader.Name)
            {
            case "position":
              builder.Append(" ").Append(stringvalue).Append("\t");
              break;
            case "name":
              string longname = stringvalue.PadRight(30);
              Console.WriteLine("{0} {1}", longname, longname.Length);
              builder.Append(longname);
              break;
            case "laps":
              if (string.IsNullOrWhiteSpace(stringvalue))
                stringvalue = "0";
              builder.Append("  ").Append(stringvalue).Append("\t\t");
              break;
            case "seed":
              if (string.IsNullOrWhiteSpace(stringvalue))
                stringvalue = "0.000";
              builder.Append(stringvalue).Append("\t\t");
              break;
            case "elapsedTime":
              if (string.IsNullOrWhiteSpace(stringvalue))
                stringvalue = "0.000";
              builder.Append(" ").Append(stringvalue).Append("\t\t");
              break;
            case "fastLap":
              if (string.IsNullOrWhiteSpace(stringvalue))
                stringvalue = "0.000";
              stringvalue = stringvalue.PadRight(8);
              builder.Append(" ").AppendLine(stringvalue);
              linenumbers++;
              break;
            default:
              break;
            }
          }
        }
        break;
      case XmlNodeType.Text: //Display the text in each element.
        break;
      case XmlNodeType.EndElement: //Display the end of the element.
        break;
      }
    }
  }
  // Edit: Matt Heffron: 6/17/2016
  // Dealing with the Cross-thread access error:
  // Was:
  richTextBox1.Text = builder.ToString();
  // Change to:
  Action updateText = () => richTextBox1.Text = builder.ToString();
  if (richTextBox1.InvokeRequired)
    richTextBox1.Invoke(updateText);
  else
    updateText();
  // End of Edit
  colorTextbox(linenumbers);
}



此外,使用 DataGrid 控件而不是更好地呈现这样的表格数据a RichTextBox


In addition, tabular data like this would be better presented using a DataGrid control instead of a RichTextBox.


这篇关于对静态感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆