How to call a nonstatic method within a static class?

Asked

Viewed 3,386 times

3

I have the following method/function and need to call the method/function criaTimerTendencia that is within the class TagAnalogicaAtiva.

private static void VerificaEnvioDeMensagensSignalR(object sender, EventArgs e)
{
    if (ExisteTendenciaParaTag)
    {
        TagAnalogicaAtiva.criaTimerTendencia();//preciso chamar este metodo/função 
    }
}

Below is the code of the method criaTimerTendencia()

class TagAnalogicaAtiva : TagAtiva
{
    public void criaTimerTendencia()
    {
        var tendencia = Processamento.PegaTendencia(IdTag);
        timer = new System.Timers.Timer(tendencia.TempoDeColeta);
        timer.Elapsed += insereTendenciaDB;
        timer.AutoReset = true;
        timer.Enabled = true;
     }
}

Only the following error is happening:

An Object Reference is required for the non-static field, method, or Property 'Taganalogicaativa.criaTimerTendencia()'

How do I solve this problem?

  • what kind of sender? tries to make a var tipo = sender.GetType() to see the guy the sender.

  • try this TagAnalogicaAtiva tag = new TagAnalogicaAtiva (); tag.criaTimerTendencia(); Or changes ;public static void criaTimerTendencia()

  • Where the variable is declared timer? You can place more parts of this class, especially the use of timer?

  • why you have not created a Taganalogicaativa obj in the static class and accessed it ??

2 answers

8


In this case, it makes no difference whether the "outside" class is static or not. The problem of the code is that you are calling a method non-static of TagAnalogicaAtiva without first creating an instance of TagAnalogicaAtiva, this will never work.

Static members are accessible through the class, not instances. Non-static members are accessible through instances of a certain class.

Imagine it exists in the class TagAnalogicaAtiva the methods FazerAlgo() and FazerAlgoEstatico() being, respectively, non-static and static.

To call the method FazerAlgo() it is necessary to have a TagAnalogicaAtiva, in the other case this is not necessary.

var tag = new TagAnalogicaAtiva();
tag.FazerAlgo();

TagAnalogicaAtiva.FazerAlgoEstatico(); // Funciona 

Then it is necessary to create an instance of TagAnalogicaAtiva to access the method criaTimerTendencia(), since he is non-static.

var tag = new TagAnalogicaAtiva();
tag.criaTimerTendencia();

2

to access the non-static method, you must instantiate a class object:

TagAnalogicaAtiva obj = new TagAnalogicaAtiva();
obj.criaTimerTendencia();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.