Question :
I have the following method / function and I 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 for the 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 occurring:
An object reference is required for the non-static field, method, or property ‘TagAnalogicaAtiva.criaTimerTendencia ()’
How do I solve this problem?
Answer :
In this case, it makes no difference whether the “outside” class is static or not. The problem with the code is that you are calling a non-static method of TagAnalogicaAtiva
without first creating an instance of TagAnalogicaAtiva
, this will never work.
Static members are accessible through the class rather than instances. Non-static members are accessible through instances of a given class.
Imagine that there exists in the class TagAnalogicaAtiva
the FazerAlgo()
and FazerAlgoEstatico()
methods being respectively non-static and static.
To call the FazerAlgo()
method, you must have one instance of TagAnalogicaAtiva
, otherwise it 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 criaTimerTendencia()
method, since it is non-static.
var tag = new TagAnalogicaAtiva();
tag.criaTimerTendencia();
To access the non-static method, you must instantiate an object of the class:
TagAnalogicaAtiva obj = new TagAnalogicaAtiva();
obj.criaTimerTendencia();