【发布时间】:2019-03-11 16:36:01
【问题描述】:
- 为什么扩展方法在插入操作中不返回修改后的节点。
- 但在创建链接列表时它工作正常。
- 扩展方法应该返回修改后的节点。
- 执行此操作的最佳方法是什么。
- IS 扩展方法性能好
代码如下
public class Node
{
public Object Data { get; set; }
public Node NextNode { get; set; }
}
public static class ListOperations
{
public static void CreateLinkedList(this Node node, Object data)
{
if (node.Data == null)
{
node.Data = data;
}
else
{
Node newnode = new Node();
newnode.Data = data;
Node current = new Node();
current = node;
while (current.NextNode != null)
{
current = current.NextNode;
}
current.NextNode = newnode;
node = current;
}
}
public static void InsertNode(this Node node1, Object data, int position)
{
Node newnode = new Node();
newnode.Data = data;
if (position == 1)
{
newnode.NextNode = node1;
node1 = newnode;
}
}
}
class Program
{
static void Main(string[] args)
{
Node node = new Node();
//random Singly LinkedList
node.CreateLinkedList(10);
node.CreateLinkedList(11);
node.CreateLinkedList(12);
node.CreateLinkedList(13);
node.CreateLinkedList(14);
node.CreateLinkedList(15);
node.InsertNode(20, 1);// this method does not return node value what is inserted.
}
}
【问题讨论】:
-
您不能在扩展方法 (yet) 中重新分配
this。 -
InsertNode是无效的,这就是它不返回任何内容的原因 -
我该怎么办??
-
你试过调试吗?
-
为什么要为此创建扩展方法?这些是您对
Node数据类型的操作。将它们保留为您类型的方法。您的方法的定义也不合适。您的 createlist 实际上只创建一个节点。
标签: c# algorithm linked-list extension-methods