Getting value by reflection without garbage

I am writing a system that requires me to get property values ​​in an object, preferably using reflection. This project is for xbox360, which works on a compact basis and therefore has a slow garbage collector - this means that it is absolutely necessary to avoid distribution!

The only way I found this is:

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

I don't like this for two reasons:

  • Casting for potters, generics for programmers.
  • It explicitly creates garbage every time I need to get a primitive value, and it gets a box.

Is there any general method for getting a value from a property that primitives will not embed?

EDIT :: In response to Jones' answer, this code stolen from his blog does not cause allocation, the problem is solved:

        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");
        }
+3
1

getter Delegate.CreateDelegate - , , Xbox.

Delegate.CreateDelegate, - , , Xbox.

+1

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


All Articles