如何创建每个元素使用ref关键字的列表或数组,这样如果值更改,列表仍将指向原始引用所指向的内存中的新位置?
编辑:我试图创建许多对象,其唯一目的是保存对不同类别的其他对象的引用。从我的静态构造函数中查看此代码:
normal = new Type("Normal", new Type[]{ghost}, new Type[]{rock, steel}, new Type[]{});
fighting = new Type ("Fighting", new Type[]{ghost}, new Type[]{flying, poison, bug, psychic, fairy}, new Type[]{normal, rock, steel, ice, dark});
flying = new Type ("Flying", new Type[]{}, new Type[]{rock, steel, electric}, new Type[]{bug, grass, fairy});
ground = new Type ("Ground", new Type[]{flying}, new Type[]{bug, grass}, new Type[]{poison, rock, steel, fire, electric});
rock = new Type ("Rock", new Type[]{}, new Type[]{fighting, ground, steel}, new Type[]{flying, bug, fire, ice});
bug = new Type ("Bug", new Type[]{}, new Type[]{fighting, flying, poison, ghost, steel, fire, fairy}, new Type[]{grass, psychic, dark});
ghost = new Type ("Ghost", new Type[]{normal}, new Type[]{dark}, new Type[]{ghost, psychic});
steel = new Type ("Steel", new Type[]{}, new Type[]{steel, fire, water, electric}, new Type[]{rock, ice, fairy});
fire = new Type ("Fire", new Type[]{}, new Type[]{ref Rock, ref Fire, ref Water, ref Dragon}, new Type[]{Bug, Ice, Steel, Grass});//TODO: move Ice back to the end
water = new Type ("Water", new Type[]{}, new Type[]{water, grass, dragon}, new Type[]{ground, rock, fire});
grass = new Type ("Grass", new Type[]{}, new Type[]{flying, poison, bug, steel, fire, grass, dragon}, new Type[]{ground, rock, water});
electric = new Type ("Electric", new Type[]{ground}, new Type[]{grass, electric, dragon}, new Type[]{flying, water});
psychic = new Type ("Psychic", new Type[]{dark}, new Type[]{steel, psychic}, new Type[]{fighting, poison});
ice = new Type ("Ice", new Type[]{}, new Type[]{steel, fire, water, ice}, new Type[]{flying, ground, grass, dragon});
dragon = new Type ("Dragon", new Type[]{fairy}, new Type[]{steel}, new Type[]{dragon});
dark = new Type ("Dark", new Type[]{}, new Type[]{fighting, dark, fairy}, new Type[]{ghost, psychic});
fairy = new Type ("Fairy", new Type[]{}, new Type[]{poison, steel, fire}, new Type[]{fighting, ice, dragon});
问题是数组中的值仅适用于在当前创建对象之前创建的对象。因此,我希望通过ref传递每个数组的成员,以便在分配后它们将指向内存中的正确位置。
答案 0 :(得分:0)
您是否在处理值类型并希望它们是引用类型?
如果是这样,你必须做一些不愉快的事情,比如在类中包装你的值类型或做一些boxing并将其作为引用类型传递。
答案 1 :(得分:0)
您应该将其设为两步而不是一步,以便获得对象的实际引用。
您的Type
应该有这样的界面:
public class Type
{
public Type(string key)
{
// store key
}
public void Init(Type[] first, Type[] second, Type[] third)
{
// store or handle the parameters
}
}
现在你的静态构造函数可以像这样
normal = new Type("Normal");
rock = new Type ("Rock");
ghost = new Type ("Ghost");
steel = new Type ("Steel");
// other stuff here
normal.Init(new Type[]{ghost}, new Type[]{rock, steel}, new Type[]{});
// other inits here