Llame a una clase no estática con una aplicación de consola

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";
    }
}

Me sale el 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.

preguntado el 12 de junio de 14 a las 10:06

5 Respuestas

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
}

Respondido el 12 de junio de 14 a las 10:06

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();
}

Respondido el 05 de junio de 15 a las 08:06

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";
    }
}

Respondido el 12 de junio de 14 a las 10:06

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

Respondido el 12 de junio de 14 a las 10:06

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";
    }
}

Respondido el 12 de junio de 14 a las 10:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.