我是C#的新手,是“公共节点”; "下面的类中的一种新类型的构造函数? [英] I am new to C#, is "public node next; " a new type of constructor in the class below?

查看:66
本文介绍了我是C#的新手,是“公共节点”; "下面的类中的一种新类型的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 public class Node 
{
public Node next;
公共对象数据;
}





我的尝试:



代码示例当然是为链表创建一个节点类。

解决方案

No。

您正在声明一个名为Node的类:

  public   class 节点
{
...
}

在课堂上,您声明两个字段:

  public 节点接下来; 
public 对象数据;

这两个字段都声明为 public 这意味着类外的所有代码都可以访问它们,以及类中的代码。

你还没有为类声明构造函数,这意味着将使用一个空的默认构造函数。



第一个类型是Node - 这意味着它可以引用节点的另一个实例 - 这是你需要建立一个链表:每个节点都包含对链中下一个节点的引用。



这里有一些不好的想法: next data 应该以大写字母开头,应该是属性,而不是字段:

< pre lang =c#> public class 节点
{
public 节点下一个{ get ; set ;}
public object 数据{获取; set ;}
}

您不应该直接公开字段,而是可以使用属性。



您也不应该真正使用对象来包含您的数据,当您想要根据需要使用Node时会使代码复杂化检查它是什么类型的数据,并在使用之前将其转换为适当的类型。使用适合您要存储在节点中的数据的特定数据类型是一个更好,更好的主意,例如 int string ,或者你的构造类。


不,它不是构造函数。您的类更喜欢描述某种链接列表:节点包含对以下/下一个节点的引用,从而允许通过该列表导航。 对象数据节点的实际内容。


public class Node
{ 
  public Node next; 
  public Object data; 
}



What I have tried:

The code sample is of course create a node class in regards to a linked list.

解决方案

No.
You are declaring a class called Node:

public class Node
{ 
  ...
}

Within the class, you declare two fields:

public Node next; 
public Object data;

Both fields are declared as public which means that all code outside the class can access them, as well as code inside the class.
You have not declared a constructor for the class, which means that an empty default constructor will be used.

The type of the first one is Node - which means it can refer to another instance of a Node - which is what you need to build a linked list: each Node contains a reference to the next node in the chain.

There are a couple of bad ideas here: next and data should start with an uppercase letter and should really be properties, not fields:

public class Node
{ 
  public Node Next {get; set;} 
  public object Data {get; set;} 
}

You should not expose fields directly, use properties when you can instead.

You also shouldn't really use an object to contain your data, that complicates the code when you want to use the Node as you need to check what kind of data it is, and cast it to an appropriate type before you can use it. It's a much, much better idea to use a specific datatype that is appropriate to the data you are going to store in the node, like int, string, or a class of your construction.


No, it is not a constructor. Your class rather describes some kind of "linked list": a Node contains a reference to the following/next Node, thus allowing for navigating thru that "list". Object data is the actual content of the Node.


这篇关于我是C#的新手,是“公共节点”; &QUOT;下面的类中的一种新类型的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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