.NET: pasar Self a un objeto secundario

I occasionally find myself passing this or Me to a child object. Such as this condensed real-world example...

Public Class Entity

    Private mValidator as New EntityValidator()

    Readonly Property IsValid()
        Return mValidator.Validate(Me)
    End Property

End Class

Estoy preocupado por .Validate(Me). I get no warnings or Code Analysis violations, but it just feels wrong. I get nervous about infinite recursion and garbage collection.

We have memory leaks on a project and I've wondered if it was due to this. I've never been able to find any resource that addresses the issue.

Is this practice OK, or is my paranoia deserved?

preguntado el 08 de noviembre de 11 a las 19:11

I agree with @JSWork: we may be missing some bit of code that sets properties on the EntityValidator that would justify Validate() not being static, but all else being equal, it should be a static method, which would not even require an instance in the first place. -

Are you saying to make EntityValidator.Validate() static and my code to read Return EntityValidator.Validate(Me)? -

No, I think they are saying that your snippet doesn't give enough information. There's no clue in your code why EntityValidator would need to keep a reference. It looks like you pass in Me, it's validated, and the object Me is not stored in the object mValidator (but even if it were, there shouldn't be a problem). -

2 Respuestas

This will not, by itself, cause a memory leak, and there is nothing inherently wrong with passing this to another object. However, I would be wary of circumstances where the second object actually retains a reference to the passed-in object, as circular references can, in general, cause problems with understandability and maintainability.

respondido 08 nov., 11:23

Circular references are allowed in VB and in C#. A reference is essentially little more than a value of the size of a machine WORD in memory. If there's an object A and B, and if A points to B and B points to A, then A internally just holds a value that points to the actual object B and B just has a value that points to the actual object of A.

Someone else explains circular references better than I can, try this thread, about circular references and check the first answer. But in short: no, they won't harm your program and they are allowed and valid, even common.

If you want to find out where your memory leak is coming from, try memory profiling.

contestado el 23 de mayo de 17 a las 14:05

@nuzabar: What makes you think you have a memory leak? How much do you know about Garbage Collection? - JSWork

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.