How to get object references in vb.net or C #?

1

I have the following code:

Dim objeto1 as new ClasseTal
Dim objeto2 as new SubClasse
Dim objeto3 as new SubClasse

objeto2.Prop1 = objeto1

objeto3.Prop1 = objeto1

I want to count the reference number of objeto1 , in this case it would have to be 2, since it is in objeto2 and objeto3 .

    
asked by anonymous 29.06.2018 / 20:29

1 answer

0

As far as I know, .NET does not tell you how many references an object has programmatically, since it is GC's job to manage references.
C # - Get number of references to object
In it a user says that counting the references can be dangerous because there may be circular reference cases. Home But you can also build a "Manager" that counts the number of references using WeakReference  and a dictionary.
Here's a basic example to get a feel for. (There may be a logic error)

using System;
using System.Collections.Generic;
using System.Linq;

namespace HelperStack
{
    public static class ContadorHelper
    {

        /*
         * var objeto1 as new ClasseTal
         * var objeto2 as new SubClasse
         * var objeto3 as new SubClasse
         *
         * objeto2.Prop1 = objeto1.ObterReferencia()
         *
         * objeto3.Prop1 = objeto1.ObterReferencia()
         * Console.log(objeto1.ObterContador())
         */
        private static Dictionary<int, Dictionary<WeakReference, int>> Referencias { get; set; } = new Dictionary<int, Dictionary<WeakReference, int>>();
        /// <summary>
        /// Use esta função toda vez que quiser usar a referencia do objeto em outro local
        /// </summary>
        /// <param name="obj">Objeto qualquer.</param>
        /// <returns></returns>
        public static object ObterReferencia(this object obj)
        {
            AtualizarLista();

            if (Referencias.Count(x => x.Key == obj.GetHashCode()) > 0)
            {
                var aux = Referencias[obj.GetHashCode()].FirstOrDefault();
                if (aux.Equals(default(KeyValuePair<WeakReference, int>)))
                {
                    //Retorna uma unica referencia
                    Referencias[obj.GetHashCode()].Add(new WeakReference(obj), 1);
                    return obj;
                }
                else
                {
                    Referencias[obj.GetHashCode()][aux.Key] = aux.Value + 1;
                    //Retorna uma referencia do objeto
                    return aux.Key.Target;
                }
            }
            else
            {
                //Cria uma nova estrutura
                Referencias.Add(obj.GetHashCode(), new Dictionary<WeakReference, int>());
                Referencias[obj.GetHashCode()].Add(new WeakReference(obj), 1);
                return obj;
            }
        }
        public static int ObterContador(this object obj)
        {
            AtualizarLista();

            if (Referencias.Count(x => x.Key == obj.GetHashCode()) > 0)
            {
                //Obtem a quantodade 
                return Referencias[obj.GetHashCode()].First().Value;
            }
            else
            {
                //Caso não exista referencia do objeto
                return -1;
            }
        }
        private static void AtualizarLista()
        {
            List<int> remover = new List<int>();
            foreach (var objRef in Referencias)
            {
                //Verifica se o GC coletou o objeto
                if (objRef.Value.First().Key.IsAlive)
                {
                    remover.Add(objRef.Key);
                }
            }

            foreach (var keys in remover)
            {
                Referencias.Remove(keys);
            }
        }
    }
}
    
01.07.2018 / 04:58