我写了一系统,该系统要求我提取价值的属性,在一个目的,最好采用的反思。这个项目是为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

我不喜欢这2个原因:

  • 铸造用于陶瓷、泛型是程序员
  • 它显然创造的垃圾每一次我要得到一个原始价值,并得到装箱。

是有一些通用的方法获得的价值从一个酒店,这将不框元?

编辑::在应对附近的答案,这些代码被盗从他博客不会造成的拨款,问题的解决:

        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 -我不知道是否这就是支持上述契约框架,版本使用的Xbox虽然。

我有一个 博客Delegate.CreateDelegate 你可能找到有用的-但是,你需要看看有多少适用于Xbox。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top