English 中文(简体)
不产生垃圾,通过反射获取值。
原标题:Getting a value by reflection without 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 is for potters, generics is for programmers
  • It obviously creates garbage every time I have to get a primitive value and it gets boxed.

有没有一种通用的方法来获取属性的值,不会装箱原始类型?

回应 Jon 的答案,从他的博客中盗用的这个代码不会导致分配,问题已解决:

        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方法创建一个委托 - 我不知道Xbox使用的紧凑框架版本是否支持。

我有一篇关于Delegate.CreateDelegate博客文章,你可能会觉得有用-但是,你需要看看其中有多少适用于Xbox。

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签