我想知道如何在不改变所有引用的情况下将类的引用更改为另一个引用,例如: 在C#中使用不安全指针我可以用Vertex0替换Vertex1只需重新分配struct的地址:
class Program
{
public struct Vertex
{
public int data;
public Vertex(int data) { this.data = data; }
public override string ToString() { return data.ToString(); }
}
public unsafe struct Edge
{
public Vertex* v0, v1;
public Face* f0, f1;
public override string ToString() { return string.Format("e({0},{1})", (*v0), (*v1)); }
}
public unsafe struct Face
{
public Vertex* v0, v1, v2;
public Edge* e01, e12, e20;
public override string ToString() { return string.Format("f[{0},{1},{2}]", (*v0), (*v1), (*v2)); }
}
public unsafe static void Main(string[] args)
{
// assign address of vertex
Vertex P0 = new Vertex(0);
Vertex P1 = new Vertex(1);
Vertex P2;
Face FA = new Face { v0 = &P0, v1 = &P1, v2 = &P2 };
Face FB = new Face { v0 = &P0, v1 = &P2, v2 = &P1 };
Edge e01 = new Edge { v0 = &P0, v1 = &P1 };
Edge e12 = new Edge { v0 = &P1, v1 = &P2 };
Edge e20 = new Edge { v0 = &P2, v1 = &P0 };
//link face -> edge
e01.f0 = &FA; e01.f1 = &FB;
e12.f0 = &FA; e12.f1 = &FB;
e20.f0 = &FA; e20.f1 = &FB;
//link edge -> face
FA.e01 = &e01; FA.e12 = &e12; FA.e20 = &e20;
FB.e01 = &e20; FA.e12 = &e12; FA.e20 = &e01;
// example : collapse P0 to P1
Vertex* p0 = &P0;
*p0 = P1;
Console.WriteLine("");
}
}
使用Class而不是Struct这不起作用,因为如果我想用Vertex0更改Vertex1,我需要在所有属性中分配Vertex0(因此对于每个面和每个边)。 P0 = P1仅改变P0值,而不改变面和边类中的所有参考值。
代码工作但使用指针会使代码变得非常复杂。定义广告指针数组(Vertex * [] v)无法完成,因为visual studio说“我无法获得结构的大小”... 等...