前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#笔记:使用Unsafe代码与结构体

C#笔记:使用Unsafe代码与结构体

作者头像
超级大猪
发布2019-11-22 11:41:49
1.3K0
发布2019-11-22 11:41:49
举报
文章被收录于专栏:大猪的笔记大猪的笔记

首先打开:属性-生成-允许不安全代码开关。

开始编码:

代码语言:javascript
复制
unsafe private void DoAction_Click(object sender, RoutedEventArgs e)
{
    Node* list = CreateLinkList(new int[] { 1, 2, 3, 4 });

    while(list->next!=null)
    {
        this.result.Content += (list->data).ToString() + "##";
        list = list->next;
    }
}

unsafe private Node* CreateLinkList(int[] inputList)
{
    int length = inputList.Length;

    Node* root = null;
    root = CreateNode(0, "root 分配内存失败!");
    root->next = null;

    Node* listTail = root;//定义一个位置指针,指向链表尾

    fixed (int* pIntStart = inputList) //操作一个托管对象要先fix一下。找到地址。
    {
        int* pInt = pIntStart;//引用一个临时指针用来指向传入的inputList

        //开始循环创建链表
        for (int i = 0; i < length; i++)
        {
            if(pInt==null)
            {
                throw new Exception("粗大事了!!!未知错误使传入数组为null");
            }

            Node* temp = CreateNode(*pInt, "节点 分配内存失败");
            temp->next = null;

            //把新增节点加入到前一个节点
            listTail->next = temp;

            listTail = listTail->next;//把位置指针指向下一个节点
            pInt++;//指向数组的指针往后指一位
        }
    }
    return root;
}

unsafe private Node* CreateNode(int data, string errMsg)
{
    Node* temp = null;
    temp = (Node*)Marshal.AllocHGlobal(sizeof(Node));//尝试分配节点内存
    if (temp == null)
    {
        throw new NullReferenceException(errMsg);
    }

    temp->data = data;

    return temp;
}


unsafe struct Node
{
    public int data;
    public Node* next;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-01-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档