我如何访问私有列表< T>成员? [英] How can I access private List<T> members?

查看:70
本文介绍了我如何访问私有列表< T>成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在C#中,使用List比使用T []更方便.但是,有时分析器显示List与本机实现的大容量操作(例如Array.Copy和Buffer.BlockCopy)相比具有明显的性能损失.另外,不可能获得指向List<>元素的指针.

In general, in C# it is more convenient to use List than T[]. However, there are times when the profiler shows that List has significant performance penalties compared to natively-implemented bulk operations like Array.Copy and Buffer.BlockCopy. In addition, it is not possible to get pointers to List<> elements.

这使在Unity中使用动态网格物体有些痛苦.如果我们可以访问 T [] List._items ,则可以缓解其中的一些问题.是否可以在没有大量开销的情况下执行此操作? (CPU或垃圾)

This makes working with dynamic meshes in Unity somewhat painful. Some of these problems could be alleviated if we could access T[] List._items. Is this possible to do without significant overhead? (either CPU or garbage)

推荐答案

如果您知道List的布局,则可以使用肮脏的技巧来强制转换托管对象引用.除非您愿意在运行的每个目标平台上进行测试,并在每次Unity升级时进行重新测试,否则请不要使用它.

If you know the layout of List, then you can use a dirty trick to cast managed object references. Do not use this unless you're willing to test on every target platform you run on, and re-test with every Unity upgrade.

最危险的事情是它破坏了对象的运行时和编译类型的不变性.编译器将为TTo类型的对象生成代码,但是该对象的RTTI字段仍将显示TFrom类型的对象.

The most dangerous thing about this is that it breaks invariants about the runtime and compiled type of the object. The compiler will generate code for an object of type TTo, but the object's RTTI field will still show an object of type TFrom.

  [StructLayout(LayoutKind.Explicit)]
  public struct ConvertHelper<TFrom, TTo>
      where TFrom : class
      where TTo : class {
    [FieldOffset( 0)] public long before;
    [FieldOffset( 8)] public TFrom input;
    [FieldOffset(16)] public TTo output;

    static public TTo Convert(TFrom thing) {
      var helper = new ConvertHelper<TFrom, TTo> { input = thing };
      unsafe {
        long* dangerous = &helper.before;
        dangerous[2] = dangerous[1];  // ie, output = input
      }
      var ret = helper.output;
      helper.input = null;
      helper.output = null;
      return ret;
    }
  }

  class PublicList<T> {
    public T[] _items;
  }

  public static T[] GetBackingArray<T>(this List<T> list) {
    return ConvertHelper<List<T>, PublicList<T>>.Convert(list)._items;
  }

这篇关于我如何访问私有列表&lt; T&gt;成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆