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);
}
}
}
}