c# - 通过无垃圾反射获得值(value)

标签 c# reflection garbage

我正在编写一个系统,它要求我获取对象中属性的值,最好使用反射。这个项目是针对 xbox360 的,它在紧凑的框架上运行,因此垃圾收集器速度很慢 - 这意味着我避免分配是绝对重要的!

我找到的唯一方法是:

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

我不喜欢这个有两个原因:

  • Casting 是给陶艺家的,泛型是给程序员的
  • 显然,每次我必须获取一个原始值并且它被装箱时,它都会产生垃圾。

是否有一些通用方法可以从属性中获取值,而不是装箱基元?

EDIT::响应 Jons 的回答,从他的博客中窃取的这段代码不会导致分配,问题已解决:

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

最佳答案

一种替代方法是使用 Delegate.CreateDelegate 从 getter 方法创建委托(delegate)- 我不知道 Xbox 使用的紧凑型框架版本是否支持它。

我有一个 blog postDelegate.CreateDelegate 上,您可能会发现它很有用 - 但同样,您需要查看其中有多少适用于 Xbox。

关于c# - 通过无垃圾反射获得值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2378195/

相关文章:

c# - BeginInvoke() 有时会中断 (System.InvalidOperationException),并在阅读器关闭时尝试调用 Read 无效

Java Reflection - 多维 float 组类

c# - 不使用反射无法降低工厂方法中的圈复杂度

java - 复制构造函数创建垃圾对象

c++ - 在 devkit pro 中在图像上显示文本时屏幕顶部出现垃圾

c# - System.Reflection.TypeAttributes 是带有 FlagsAttribute 的病态枚举类型吗?

c# - BackgroundWorker 不与 TeamCity NUnit runner 一起工作

c# - Xamarin.GooglePlayServices.Ads : how to add a bundle to the ad request

reflection - .NET 世界中的 "mark a field as literal"是什么意思?

c++ - 为什么我的char *复印机返回不同的东西?