如何做一个"指针指向"在C#中? [英] How to do a "Pointer to Pointer" in C#?

查看:102
本文介绍了如何做一个"指针指向"在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似列表的数据结构,但我不能使用任何内置容器(列表<>等)。我想保持一个指针的指针又名尾巴,这点到此列表的尾部。它应该像这样C ++:

I have a data structure similar to a List, but I could not use any built-in containers (List<> etc.). I'd like to keep a "pointer to pointer" aka "tail", which point to the tail of this list. It should like this in C++:

class MyList {
  Node* head;
  Node** tail;  // tail is just a pointer to the "next" pointer of the end of the list.
  MyList() {
    head = null;
    tail = &head;
  }
  bool isEmpty() {
    return head == null;
  }
  void add(int val) {
    *tail = new Node();
    (*tail)->val = val;
    tail = &((*tail)->next);
  }
}



如何实现这在C#?谢谢!

How to implement this in C#? Thanks!

推荐答案

您说的没错,C#不能(安全)实现一个指针到指针。作为像您这样的结果可爱的代码是不可能的。这是我能做的最好的。

You're right, C# cannot (safely) implement a pointer-to-pointer. As a result cute code like yours is not possible. This is the best I can do.

public class Node {
  public Node next;
  public int val;
}
class MyList {
  Node head = null;
  Node tail = null;
  public MyList() { }
  bool isEmpty() {
    return head == null;
  }
  void add(int val) {
    if (isEmpty())
      head = tail = new Node();
    else {
      tail.next = new Node();
      tail = tail.next;
    }
    tail.val = val;
  }
}



这不是坏的,是吗?几乎一模一样的长度和(我认为)。稍微容易理解

It's not bad, is it? Almost exactly the same length and (I would argue) slightly easier to understand.

有C ++中强大的功能,是不是在C#中可用,但在我的经验C#是一个显著更高效的语言,即使是这样的低级代码。

There are powerful features in C++ that are not available in C#, but in my experience C# is a significantly more productive language, even for low level code like this.

如果你有,你认为不会屈服于这种简单的翻译的一些其他的代码请邮寄和我们将看到我们能做些什么。

If you have some other code that you think will not yield to this kind of simple translation please post and we'll see what we can do.

这篇关于如何做一个&QUOT;指针指向&QUOT;在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆