Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Trying To Understand Events
Message
De
18/02/2009 15:26:37
Mike Cole
Yellow Lab Technologies
Stanley, Iowa, États-Unis
 
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Divers
Thread ID:
01382673
Message ID:
01382745
Vues:
45
Step into the ReaderRetrieved() method to get the actual line that produced the error. Also, it appears you should name the method OnReaderRetrieved instead of just ReaderRetrieved.

>Excellent. Thanks.
>
>However, I'm now getting the same error at runtime on this line in my class:
>
>
>if (_oException == null)
>{
>    ReaderRetreived();  // Erroring here at runtime
>}
>
>
>Error: "Object reference not set to an instance of an object."
>
>
>
>
>
>>>I am trying to understand events. Coming from VFP where there are no user-definabnle events, it's a bit of a curve for me.
>>>
>>>I wrote this class which returns a SqlDataReader, and which contains an event:
>>>
>>
>>> if (_oException == null)
>>> {
>>> ReaderRetreived();
>>> }
>>>
>>> return oReader;
>>
>>The above code will fail if you don't have anyone subscribed to the event. You need to check if it's null or not.
>>
>>
>>if (ReadRetreived != null)
>>   ReaderRetreived();
>>
>>
>>Also, it's a common/best practice to call an event from a single method called "OnEventName", ex.
>>
>>
>>public virtual void OnReaderRetrieved()
>>{
>>   if (ReaderRetrieved != null)
>>      ReaderRetrieved();
>>}
>>
>>
>>
>>In this case, it's complaining because an event handler requires a real instance of an object in order to hook up the event. You're inside of a static method, which means you don't have an instance reference. In this case you can make your method call static and it will work:
>>
>>
>>private static void ReaderRetreived()
>>{
>>    while (oReader.Read())
>>    {
>>        // Some code here
>>    }
>>}
>>
>>
>>Or, move the code in this method out to a new class, instanciate the class, then hook up the event (basically get it out of the static method)
>>
>>BTW - the event hook up code can be shortened to:
>>
>>
>>   oBank.ReaderRetreived += new ReaderRetreivedEvent(ReaderRetrieved);
>>   // Can also be shorted to:
>>   oBank.ReaderRetreived += ReaderRetrieved;
>>}
>>
>>
Very fitting: http://xkcd.com/386/
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform