我在c#中创建了自定义链接列表。
LinkedList.cs:
class LinkedList
{
private Node Start;//Mazgas pr
private Node End;//Mazgas pb
private Node Current;// Mazas d saraso sasajai
public LinkedList()
{
this.Start = null;
this.End = null;
this.Current = null;
}
public Object Get(int index)
{
for( Node curr = Start; curr != null; curr = curr.Next)
{
if( curr.Index == index )
return curr.Data;
}
return null;
}
public void PrintData()
{
for (Node curr = Start; curr != null; curr = curr.Next)
{
Console.WriteLine("{0}: {1}", curr.Index, curr.Data);
}
}
public int Count()
{
int i = 0;
for( Node curr = Start; curr != null; curr = curr.Next, i++);
return i;
}
public void Add(Object data)
{
Node current = new Node(data, null);
if (Start != null)
{
End.Next = current;
End.Next.Index = End.Index + 1;
End = current;
}
else
{
Start = current;
End = current;
End.Index = 0;
}
}
}
Node.cs:
class Node
{
public Object Data { get; set; }
public Node Next { get; set; }
public int Index { get; set; }
public Node() { }
public Node(Object data, Node next )
{
Data = data;
Next = next;
}
public override string ToString ()
{
return string.Format ("Data: {0}", Data);
}
}
和Part.cs
class Part
{
public string Code { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public Part(string code, string name, double price)
{
Code = code;
Name = name;
Price = price;
}
public Part() { }
public override string ToString()
{
return string.Format("{0} {1}", Name, Code);
}
}
问题是,当我创建列表LinkedList parts = new LinkedList()
时
并向其添加对象parts.Add(new Part("code", "name", 10));
我无法访问零件对象变量。我需要这样做:
for( int i=0; i<parts.Count(); i++)
{
Console.WriteLine("{0}", (Part)Parts.Get(i).Name);
}
但它给了我错误:
错误CS1061:输入&#39;对象&#39;不包含&#39;姓名&#39;的定义 没有推广方法&#39;姓名&#39;类型&#39;对象&#39;可以找到。是 你错过了一个装配参考? (CS1061)
EDITED:我需要这个链表对任何类型的对象都是灵活的。
答案 0 :(得分:1)
CarAdapter carAd;
if (adapter instanceOf CarAdapter){
carAd = (CarAdapter) adapter;
}
相当于(Part)Parts.Get(i).Name
,并且由于(Part)(Parts.Get(i).Name)
的返回值属于Get(i)
且对象没有object
属性,因此您收到了例外。
你可以这样纠正:
Name
注意:强>
Generic
课程。拥有通用((Part)Parts.Get(i)).Name
和Node<T>
类,您可以更改输入参数并将值返回LinkedList<T>
而不是T
。LinkedList<T>
或其他可用的通用数据结构。