Ottenere un valore di riflessione, senza spazzatura
-
24-09-2019 - |
Domanda
Sto scrivendo un sistema che mi obbliga a recuperare i valori delle proprietà in un oggetto, preferibilmente utilizzando la riflessione. Questo progetto è per la Xbox 360, che corre sul quadro compatto ed ha una lenta garbage collector in tal modo - questo significa che è assolutamente vitale che evito allocazioni
L'unico modo che ho trovato per fare questo è:
Foo Something; //an object I want to get data from
PropertyInfo p; //get this via reflection for the property I want
object value = p.GetGetmethod().Invoke(Something, null);
//Now I have to cast value into a type that it should be
Non mi piace questo per 2 motivi:
- Il casting è per i ceramisti, i farmaci generici sono per i programmatori
- Si crea ovviamente spazzatura ogni volta che devo avere un valore di base e si ottiene in scatola.
C'è qualche metodo generico per ottenere il valore da una proprietà, che non sarà casella primitive?
EDIT :: In risposta a Jons risposta, il codice rubato dal suo blog non causa allocazioni, problema risolto:
String methodName = "IndexOf";
Type[] argType = new Type[] { typeof(char) };
String testWord = "TheQuickBrownFoxJumpedOverTheLazyDog";
MethodInfo method = typeof(string).GetMethod(methodName, argType);
Func<char, int> converted = (Func<char, int>)Delegate.CreateDelegate
(typeof(Func<char, int>), testWord, method);
int count = GC.CollectionCount(0);
for (int i = 0; i < 10000000; i++)
{
int l = converted('l');
if (GC.CollectionCount(0) != count)
Console.WriteLine("Collect");
}
Soluzione
Un'alternativa sarebbe quella di creare un delegato dal metodo getter utilizzando Delegate.CreateDelegate
-. non so se questo è supportato dalla versione compact framework usato dalla Xbox se
Ho un blog post su Delegate.CreateDelegate
che si possono trovare utili -. ma ancora una volta, avrete bisogno di vedere come gran parte di essa è applicabile alla Xbox