[英]Obscure unsafe code behaviour in c#
最近,我写了一些树,想尝试不安全的代码。 最终,我在不安全的情况下做了所有工作,但是在这段代码中找到了一些晦涩的地方(对于我来说)(对于较短的代码,我删除了所有逻辑,因此所有代码看起来都毫无意义):
public static void Main() {
EqClass a = new EqClass();
a.AddElement(2, new record(3)); // *place1*
...
}
unsafe struct node {
public node* next;
public record Value;
public node(record value) {
this = new node();
this.Value = value;
}
}
struct record {
public int a;
public record(int a) {
this.a = a;
}
}
unsafe class EqClass {
node*[] last = new node*[3];
public void AddElement(int classIndex, record element) {
node a = new node(element);
node* newNode = &a;
last[classIndex]->next = newNode; // *place2*
}
}
在place2中可以,但是当AddElement
方法结束时,在last [2](我们放置元素的位置)中意外出现了一些垃圾。 但为什么? 先感谢您。
这不是 unsafe
, *
的用途。 认真:不要这样做。 您在这里所做的基本上是参考。 为此:使用class
而不是struct
。 否则,这会非常非常非常地伤害您。
另外:这不是struct
目的。 看着这样一个可变的struct
,马上就告诉我,您并没有意识到struct
的意图。
如果您想知道废话值从何而来:指针不指向固定位置。 解决方法不是“哦,所以我需要固定它们”。 它是“使用引用,而不是指针”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.