Call a non-static class with a console application

2019-06-19 00:59发布

问题:

I'm trying to call a method from another class with a console application. The class I try to call isn't static.

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        var myString = p.NonStaticMethod();
    }

    public string NonStaticMethod()
    {
        return MyNewClass.MyStringMethod(); //Cannot call non static method
    }
}

class MyNewClass
{
    public string MyStringMethod()
    {
        return "method called";
    }
}

I get the error:

Cannot access non-static method "MyStringMethod" in a static context.

This works if I move the MyStringMethod to the class program. How could I succeed in doing this? I cannot make the class static nor the method.

回答1:

Just like you create an instance of the Program class to call the NonStaticMethod, you must create an instance of MyNewClass:

public string NonStaticMethod()
{
    var instance = new MyNewClass();
    return instance.MyStringMethod(); //Can call non static method
}


回答2:

Non static class need an instance to access its members.

Create the instance inside the static Main method and call non static class member:

static void Main(string[] args)
{
    MyNewClass p = new MyNewClass();
    var myString = p.MyStringMethod();
}


回答3:

If you want to call a member function of a non-static class then you have to create its instance and then call its required function.

So for calling MyStringMethod() of non-static class MyNewClass, do this:

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        var myString = p.NonStaticMethod();
    }

    public string NonStaticMethod()
    {   
        MyNewClass obj = new MyNewClass();
        if(obj != null)
            return obj.MyStringMethod();
        else
            return "";
    }
}

class MyNewClass
{
    public string MyStringMethod()
    {
        return "method called";
    }
}


回答4:

Non static methods need an instance. You should create it the same way you create a Program to call its non static method.



回答5:

You need to create an Instance of MyNewClass

class Program
{
    //instantiate MyNewClass
    var myNewClass = new MyNewClass();

    static void Main(string[] args)
    {
        Program p = new Program();
        var myString = p.NonStaticMethod();
    }

    public string NonStaticMethod()
    {
        //use the instance of MyNewClass
        return myNewClass.MyStringMethod(); //Cannot call non static method
    }
}

class MyNewClass
{
    public string MyStringMethod()
    {
        return "method called";
    }
}