简体   繁体   中英

Accessing Methods Within a Class (C#)

I have a very simple question. This being said, I have tried to solve it by searching through stackexchange's previously answered questions but I came up short. This is because I want to know how to tell the program's entry point to access other classes.

I had previously written a simple finite state machine but the code got congested because I did not know how to break it up into classes. In my new program, I am trying to break it up so it can be better managed.

The entry point starts off by accessing the class I created, NewState() . If you run the code, you will observe that despite it compiling correctly, the function inside NewState() does not produce the Console.WriteLine statement I wanted it to.

So, my question is this:

How do I make my code access the static void State() method within the NewState class and display the Console.WriteLine statement?

Program class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Finite_State_Machine_3
{
    class Program
    {
        static void Main(string[] args)
        {
            new NewState();
        }
    }
}

NewState class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Finite_State_Machine_3
{
    class NewState
    {
        static void State()
        {
                Console.WriteLine("Hello world");
        }
    }
}

The method is static, so instead of creating an instance, make the State method public and try this

static void Main(string[] args)
{
    NewState.State();
}

But if you're going to be calling it like that, you'd probably be better off putting it in the same class.

class Program
{
    static void Main(string[] args)
    {
        State();
    }

    static void State()
    {
        Console.WriteLine("Hello world");
    }
}

If you do want it in a separate class and call it from an instance of that class, you need to make the State method non-static (as well as public) and call it from the instance

class Program
{
    static void Main(string[] args)
    {
        NewState MyVariable = new NewState();
        MyVariable.State();
    }
}


class NewState
{
    public void State()
    {
        Console.WriteLine("Hello world");
    }
}

If it's static, then you'll call it from the class not from the instance.

So,

NewState.State()

That said, if I remember my design patterns right you actually want to be passing instances around, not using static methods.

您需要将方法设置为public staticinternal static ,然后通过调用NewState.State()进行调用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM