我正在尝试创建一种简单的方法让我的链表在C#中像循环链表一样。
我有这个代码,它不希望显示为扩展方法。知道为什么吗?
static class CircularLinkedList
{
public static LinkedListNode<object> NextOrFirst(this LinkedListNode<object> current)
{
if (current.Next == null)
return current.List.First;
return current.Next;
}
public static LinkedListNode<object> PreviousOrLast(this LinkedListNode<object> current)
{
if (current.Previous == null)
return current.List.Last;
return current.Previous;
}
}
答案 0 :(得分:3)
LInkedListNode<T>
代替LinkedListNode<object>
码
public static class CircularLinkedList
{
public static LinkedListNode<T> NextOrFirst<T>(this LinkedListNode<T> current)
{
if (current.Next == null)
return current.List.First;
return current.Next;
}
public static LinkedListNode<T> PreviousOrLast<T>(this LinkedListNode<T> current)
{
if (current.Previous == null)
return current.List.Last;
return current.Previous;
}
}
答案 1 :(得分:2)
您必须在课堂上指定public
。您的类是内部的,可能是因为如果您的扩展类位于不同的项目中,则无法访问扩展方法。
public static class CircularLinkedList
{
.....
}
要稍后访问它,请使用它:
LinkedListNode<object> obj = new LinkedListNode<object>(null);
obj.PreviousOrLast();
答案 2 :(得分:1)
在以下应用程序中,这对我来说很好用:
class Program
{
static void Main(string[] args)
{
LinkedListNode<object> node = new LinkedListNode<object>("Hello World");
node.NextOrFirst();
}
}
static class CircularLinkedList
{
public static LinkedListNode<object> NextOrFirst(this LinkedListNode<object> current)
{
if (current.Next == null)
return current.List.First;
return current.Next;
}
public static LinkedListNode<object> PreviousOrLast(this LinkedListNode<object> current)
{
if (current.Previous == null)
return current.List.Last;
return current.Previous;
}
}
确保使用正确的泛型类型实例化LinkedListNode,因为使用任何其他类型(即字符串)将不起作用。但是,您可以通过将代码更改为以下内容来扩展它以支持任何类型的LinkedListNode:
class Program
{
static void Main(string[] args)
{
LinkedListNode<string> node = new LinkedListNode<string>("Hello World");
node.NextOrFirst<string>();
LinkedListNode<int> node2 = new LinkedListNode<int>(3);
node2.NextOrFirst<int>();
}
}
static class CircularLinkedList
{
public static LinkedListNode<T> NextOrFirst<T>(this LinkedListNode<T> current)
{
if (current.Next == null)
return current.List.First;
return current.Next;
}
public static LinkedListNode<T> PreviousOrLast<T>(this LinkedListNode<T> current)
{
if (current.Previous == null)
return current.List.Last;
return current.Previous;
}
}