A method can access the properties of the object it belongs to when stored through a delegate?

Asked

Viewed 78 times

5

I’m building a dictionary of the following kind: <string, delegate>, that will access a method belonging to an object of the following class:

class Example{

   public int Power { get; set; }
   public int Defense { get; set; }

   public void Method(){

      Console.WriteLine("Power: " + Power + " Defense: " + Defense);

   }

}

As seen, the method depends on the properties of the class object, as it has to access the Power and the Defense. If I store the method, through a delegate in the dictionary and rotate it from a Dicionario["string"](); will it be able to access the properties of the object to which the method belongs? If so, how?

1 answer

4


A method accessed through a delegate is no different than any other method, as long as the access is done through a valid object for that type can access everything that is public without problems, and if the access is internal even more, then you can access even what is private. Of course, if you don’t have an object like Example you will not be able to access, but this is valid regardless of whether you are using a delegate or not. What is showing accesses internally then shouldn’t even be a question. The method doesn’t know what it’s called, so it doesn’t even matter if it’s delegate or not. In this specific case I see no problem in what you are doing, unless you have done something not shown in the question.

Browser other questions tagged

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