Accessing a private method from another class

I have two repository classes ( RepositoryFactory and BaseRepository ) that implement different interfaces in one project. The BaseRepository class has a private method, which is now needed in another class with the same implementation.

Instead of duplicating the method in order to keep it confidential, I was thinking about a possible alternative, although so far I have not been able to find a good solution, since by definition a private method has scope only in its own class.

Using inheritance and changing the method to "protected" would also not be an option, since the two classes are not connected semantically. I cannot use a public property that returns the result of a method, because the return type is not valid.

+6
source share
3 answers

It is not possible to accomplish what you want in C #. The closest you can do is internal , which makes the element visible to the entire assembly. It would also be possible to make two classes private and nested inside another class, but this is not always appropriate.

Mads Torgersen, which works in C #, has to say this:

I saw a number of sentences trying to grasp some notion of “accessibility of a set of classes”. Of course, the complication is that, unlike the existing capabilities, there is no natural group (each, assembly, derived classes, one class) to link it, so even with the help of another accessibility modifier you also need syntax (or something else) to identify the group.

There are several ways to cut it. I have not seen suggestions that are obviously correct, but I think the problem is relevant, and I will take this with the development team.

( source )

+7
source

You can use reflection. Here is an example:

 MethodInfo privMethod = objInstance.GetType().GetMethod("PrivateMethodName", BindingFlags.NonPublic | BindingFlags.Instance); privMethod.Invoke(objInstance, new object[] { methodParameters }); 
+12
source

You can, but it looks awkward. This allows nested classes to access private materials from the containing class. However , even if something is possible, it does not mean that you should do it . If you just change the modifier to internal , you will get the same behavior, and since the two classes are connected together, it makes sense to send them to the same assembly, so the internal modifier is the correct answer.

 public class BaseRepository { public sealed class RepositoryFactory { public static BaseRepository Create() { var repo = new BaseRepository(); repo.MethodRequiredByRepositoryFactory(); return repo; } } private void MethodRequiredByRepositoryFactory() { } } 
+4
source

Source: https://habr.com/ru/post/922566/


All Articles