gpt4 book ai didi

c# - 模糊 C# 中的不安全代码行为

转载 作者:行者123 更新时间:2023-12-02 12:15:57 24 4
gpt4 key购买 nike

最近我写了一些树,想尝试不安全的代码。最后,我所做的一切都没有不安全,但在这段代码中发现了一些晦涩的(对我来说)地方(对于较短的代码,我删除了所有逻辑,因此所有代码看起来毫无意义):

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](我们放置元素的地方)意外地出现了一些垃圾。但为什么?预先感谢您。

最佳答案

不是不安全*的用途。说真的:不要这样做。您在这里所做的本质上是引用。为此:使用,而不是结构。否则这会对你造成非常非常严重的伤害。

另外:这不是 struct 的用途。看着像这样的可变 struct ,我立刻就知道您没有意识到 struct 的用途。

如果您想知道无意义值来自哪里:指针不是指向固定位置。解决这个问题的方法不是“哦,所以我需要固定它们”。它是“使用引用,而不是指针”。

关于c# - 模糊 C# 中的不安全代码行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23115973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com