C# 需要传递一个对象,以便另一个类可以调用它的方法来更新它

发布于 2024-11-09 07:50:47 字数 2946 浏览 0 评论 0原文

我有一堂课,其中有 3 个公共列表。它基本上只是一个数据保存类。

我有一个带有 xml 之类的分隔符的文件(某种类型的乞求和结束标签,以及中间的数据值)

我有一个解析类,它检测数据保存类中的某些内容并将其添加到某些列表中。基本上我正在尝试检测开始标签,将其存储在我的数据保存类的开始标签列表中。

我试图采用的方式(基于老师的糟糕借口)是 Main() 将数据保存类实例化为一个对象,对于解析类也是如此。然后,它调用 ParseMain 来解析文件,并将标签、数据值和结束标签分离到数据保存类内各自的 List 中。然后,在 Parse 类完成后,回到 main,我调用数据类内的方法来显示数据。

我基本上被编译器大喊大叫,因为即使 xml 数据持有者类已在 main 中实例化,它也不会或无法添加到公共列表中,我特别收到此错误

“需要对象引用非静态字段、方法或属性”

如何从我的解析类中设置数据读取类列表?

我的老师给出了一个可怕的例子(除了标记为静态的类之外,他拥有所有内容,并且基本上只是将 java/c++ 样式代码放入几个类中)

这对于我所在的基础编程课程来说都是额外的学分。(正常版本是所有结构都在一个类中)

***编辑-添加代码片段

                    XMLDoc XMLData = new XMLDoc();
                    XMLParse parseXML1 = new XMLParse();


                    //Calls the parseXML1 method passing it
                    //the name of the currently opened file.
                    parseXML1.MainParse(fileIn);

然后到我的主要解析

    public void MainParse(FileStream fileIn)
    {

        int byteIn;


        while ((byteIn = fileIn.ReadByte()) != -1)
        {

            if (byteIn == '<')
            {
                ParseElement(ref byteIn,fileIn);
            }

ParseElement 看起来像

    public void ParseElement(ref int byteIn,FileStream fileIn)
    {
        token += byteIn;
        //First I need to get the entire tag stored in token
        do
        {        
            byteIn = fileIn.ReadByte();
            token += byteIn;
        } while (byteIn != '>');
        token += '>';

        //now I insert a / into my compare token
        compareToken = token;
        compareToken.Insert(1,"/");

        //It's an ending tag
        if (token == compareToken)
        {
            //figure this out later
        }
        //It's an opening tag,store it into element list
        else
        {
            XMLDoc.elements.Add(token);
            //also tried XMLData/elements/Add(token)
        }

    }

,最后我的 XMLDoc 类看起来像......

class XMLDoc
{
    public List<string> elements;
    public List<string> dataValues;
    public List<string> endingElements;

    public XMLDoc()
    {
        elements = new List<string>();
        dataValues = new List<string>();
        endingElements = new List<string>();
    }

    //This method simply displays the contents of the arrays
    public void DisplayCollected()
    {
        Console.WriteLine("Begin unformatted dump");
        for (int ii = 0; ii <= elements.Count;ii++)
        {
            Console.WriteLine("\n"+elements[ii]+dataValues[ii]+
                "\n"+endingElements[ii]);
        }
        Console.WriteLine("End unformatted dump\n");
    }

    //This method will generate an xml style display
    //To add later

}

我正在玩耍,边做边学等等。在这一点上,我不得不放弃老师的例子,如上所述,他只是将每个类中的每个方法都设为静态,可能是因为他将主要实验室工作中的示例放在一起(这是结构性的,并且全部在第一类中)

I have a class that has 3 public List's in it. It's basically just a data holding class.

I have a file with xml like delimiters(begging and ending tags of some sort, and data value that goes in between)

I have a parse class, that detects and adds certain things to certain lists from the data holding class. Basically I'm trying to detect an opening tag, store it in the opening tag List in my data holding class.

The way I'm trying to go (based on the teachers poor excuse for an example) is Main() instantiates the data holding class into an object, likewise for the parse class. Then it calls ParseMain to parse through the file and separate tags, data values, and closing tags to their respective List inside the data holding class. Then after the Parse class is finished, back in main, I'm calling up methods inside the data class to display the data.

I'm basically being yelled at by the compiler because, even though the xml data holder class has been instantiated in main, it doesn't or can't add to the public List's I get specifically this error

"An object reference is required for the non-static field, method, or property"

How can I set the data reading classes List's from my parse class?

My teacher gave a horrible example (he had everything but the classes marked static, and basically just slapped java/c++ style code into a couple classes)

This is all extra credit for a basic programming class I'm in.(the normal version is all structural inside one class)

***Edit- adding code snippets

                    XMLDoc XMLData = new XMLDoc();
                    XMLParse parseXML1 = new XMLParse();


                    //Calls the parseXML1 method passing it
                    //the name of the currently opened file.
                    parseXML1.MainParse(fileIn);

then to my main parse

    public void MainParse(FileStream fileIn)
    {

        int byteIn;


        while ((byteIn = fileIn.ReadByte()) != -1)
        {

            if (byteIn == '<')
            {
                ParseElement(ref byteIn,fileIn);
            }

ParseElement looks like

    public void ParseElement(ref int byteIn,FileStream fileIn)
    {
        token += byteIn;
        //First I need to get the entire tag stored in token
        do
        {        
            byteIn = fileIn.ReadByte();
            token += byteIn;
        } while (byteIn != '>');
        token += '>';

        //now I insert a / into my compare token
        compareToken = token;
        compareToken.Insert(1,"/");

        //It's an ending tag
        if (token == compareToken)
        {
            //figure this out later
        }
        //It's an opening tag,store it into element list
        else
        {
            XMLDoc.elements.Add(token);
            //also tried XMLData/elements/Add(token)
        }

    }

and finally my XMLDoc class looks like....

class XMLDoc
{
    public List<string> elements;
    public List<string> dataValues;
    public List<string> endingElements;

    public XMLDoc()
    {
        elements = new List<string>();
        dataValues = new List<string>();
        endingElements = new List<string>();
    }

    //This method simply displays the contents of the arrays
    public void DisplayCollected()
    {
        Console.WriteLine("Begin unformatted dump");
        for (int ii = 0; ii <= elements.Count;ii++)
        {
            Console.WriteLine("\n"+elements[ii]+dataValues[ii]+
                "\n"+endingElements[ii]);
        }
        Console.WriteLine("End unformatted dump\n");
    }

    //This method will generate an xml style display
    //To add later

}

I'm playing around,learning by doing and such. I've at this point had to abandon the teachers example, as mentioned above he just made every method in every class static, probably because he slapped his example together from the main lab work(which is structural and all inside the first class)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

羞稚 2024-11-16 07:50:48

编辑:好的,看起来您只需要传递对对象的引用,例如,

XmlDoc xmlData = new XmlDoc();
XmlParser parser = new XmlParser();
parser.MainParse(xmlData, fileIn)

...

public void MainParse(XmlDoc xmlData, FileStream fileIn)
{
    ...
    ParseElement(xmlData, ref byteIn, fileIn);
    ...
}

public void ParseElement(XmlDoc xmlData, ref int byteIn,FileStream fileIn)
{
    ...
}

我已经稍微调整了名称以使其更合理。

顺便说一下,我建议您不要在 XmlDoc 中使用公共字段。公共字段违反了封装性 - 如果您确实需要公开值,则使用属性,但理想情况下将更多行为放在对象本身中。

EDIT: Okay, it looks like you just need to pass the reference to the object around, e.g.

XmlDoc xmlData = new XmlDoc();
XmlParser parser = new XmlParser();
parser.MainParse(xmlData, fileIn)

...

public void MainParse(XmlDoc xmlData, FileStream fileIn)
{
    ...
    ParseElement(xmlData, ref byteIn, fileIn);
    ...
}

public void ParseElement(XmlDoc xmlData, ref int byteIn,FileStream fileIn)
{
    ...
}

I've adjusted the names slightly to be more sensible IMO.

I would recommend that you don't use public fields in XmlDoc, by the way. Public fields violate encapsulation - use properties if you really need to just expose values, but ideally put more behaviour in the object itself.

时光礼记 2024-11-16 07:50:48

这里的错误消息非常好:“非静态字段、方法或属性需要对象引用”

您正在尝试以静态方式调用实例方法,您有两个选择:

  1. 使方法静态。
  2. 实例化类并从实例调用方法。

例如:

public class Foo()
{
    public void Frob() {}
}

你不能这样做:

Foo.Frob();

但你可以这样做:

var foo = new Foo();
foo.Frob();

或这样:

public class Foo()
{
    public static void Frob() {} // Note static
}

[...]

Foo.Frob();

The error message is pretty good here: "An object reference is required for the non-static field, method, or property"

You are trying to call an instance method in a static fashion, you have two options:

  1. Make the method static.
  2. Instantiate the class and call the method from the instance.

For example:

public class Foo()
{
    public void Frob() {}
}

You cannot do this:

Foo.Frob();

But you can do this:

var foo = new Foo();
foo.Frob();

or this:

public class Foo()
{
    public static void Frob() {} // Note static
}

[...]

Foo.Frob();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文