更新:下一版本的C#有一个正在考虑的功能,可以直接回答这个问题.cf下面的答案.
要求:
我有编译和运行的代码,它的工作原理......但是每当我访问A#时,C#都会默默地复制AoS?(完整来源见下文)
public Dictionary<System.Type, System.Array> structArraysByType;
public void registerStruct<T>()
{
System.Type newType = typeof(T);
if( ! structArraysByType.ContainsKey(newType ) )
{
structArraysByType.Add(newType, new T[1000] ); // allowing up to 1k
}
}
public T get<T>( int index )
{
return ((T[])structArraysByType[typeof(T)])[index];
}
public void set<T>( int index, T newValue )
{
((T[])structArraysByType[typeof(T)])[index] = newValue;
}
Run Code Online (Sandbox Code Playgroud)
笔记:
据我所知,您正在做的事情应该可以正常工作,但是,是的,T当您调用 时,它会返回结构实例的副本Get,并在您调用 时使用基于堆栈的实例执行替换Set。除非您的结构很大,否则这不应该是问题。
如果它们很大并且您想要
然后你可以将以下内容添加到你的类中:
public delegate void Accessor<T>(ref T item) where T : struct;
public delegate TResult Projector<T, TResult>(ref T item) where T : struct;
public void Access<T>(int index, Accessor<T> accessor)
{
var array = (T[])structArraysByType[typeof(T)];
accessor(ref array[index]);
}
public TResult Project<T, TResult>(int index, Projector<T, TResult> projector)
{
var array = (T[])structArraysByType[typeof(T)];
return projector(ref array[index]);
}
Run Code Online (Sandbox Code Playgroud)
或者简单地返回对底层数组本身的引用,如果您不需要抽象它/隐藏您的类封装它们的事实:
public T[] GetArray<T>()
{
return (T[])structArraysByType[typeof(T)];
}
Run Code Online (Sandbox Code Playgroud)
然后您可以从中简单地访问元素:
var myThingsArray = MyStructArraysType.GetArray<MyThing>();
var someFieldValue = myThingsArray[10].SomeField;
myThingsArray[3].AnotherField = "Hello";
Run Code Online (Sandbox Code Playgroud)
或者,如果没有特定原因将它们设为结构(即确保顺序缓存友好的快速访问),您可能只想使用类。
| 归档时间: |
|
| 查看次数: |
376 次 |
| 最近记录: |