简体   繁体   English

掩盖C#中不安全的代码行为

[英]Obscure unsafe code behaviour in c#

Recently I wrote some trees and want to try unsafe code. 最近,我写了一些树,想尝试不安全的代码。 Finally I do all without unsafe but find some obscure (for me) places in this code (for shorter code I delete all logic so all code looks quite pointless): 最终,我在不安全的情况下做了所有工作,但是在这段代码中找到了一些晦涩的地方(对于我来说)(对于较短的代码,我删除了所有逻辑,因此所有代码看起来都毫无意义):

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*
        }
    }

In place2 all is all right but when method AddElement ends, in last[2](where we put an element) unexpectedly appear some garbage. place2中可以,但是当AddElement方法结束时,在last [2](我们放置元素的位置)中意外出现了一些垃圾。 But why? 但为什么? Thank you in advance. 先感谢您。

This is not what unsafe and * is for. 不是 unsafe*的用途。 Seriously: do not do this. 认真:不要这样做。 What you are doing here is essentially references. 您在这里所做的基本上是参考。 For that: use a class , not a struct . 为此:使用class而不是struct This is going to hurt you very very very badly otherwise. 否则,这会非常非常非常地伤害您。

Also: this is not what struct is for. 另外:这不是struct目的。 Looking at a mutable struct like this tells me in an instant that you aren't appreciating what struct is intended to do. 看着这样一个可变的struct ,马上就告诉我,您并没有意识到struct的意图。

If you want to know where nonsense values are coming from: the pointers aren't to pinned locations. 如果您想知道废话值从何而来:指针不指向固定位置。 The fix to this is not "oh, so I need to pin them". 解决方法不是“哦,所以我需要固定它们”。 It is "use references, not pointers". 它是“使用引用,而不是指针”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM