c#访问自定义链表对象';s元素
我已经在c#中创建了自定义链表 LinkedList.cs:c#访问自定义链表对象';s元素,c#,linked-list,C#,Linked List,我已经在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
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);
}
}
及c部
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);
}
}
问题是,当我创建listLinkedList parts=newlinkedlist()时
并向其添加对象部分代码>我无法访问零件对象变量。我需要这样做:
for( int i=0; i<parts.Count(); i++)
{
Console.WriteLine("{0}", (Part)Parts.Get(i).Name);
}
for(int i=0;i(Part)Parts.Get(i).Name
相当于(Parts)(Parts.Get(i).Name)
,由于Get(i)
的返回值是对象的类型,并且对象没有Name
属性,因此收到了异常
您可以通过以下方式进行更正:
((Part)Parts.Get(i)).Name
注意:
- 我想这只是为了学习
- 如果列表中的所有项都是相同类型的,则可以创建类。使用通用的
节点
和链接列表
类,可以更改输入参数并将值返回到T
,而不是对象
- 在实际应用程序中,可以使用或使用其他可用的通用数据结构
您可以在部件类型转换周围添加额外的括号,例如;Console.WriteLine({0}),((Part)parts.Get(i)).Name);
(Part)parts.Get(i).Name
相当于(Part)(parts.Get(i).Name)
,因为Get(i)的返回值<代码>类型<代码>对象< /代码>,对象没有<代码>名称<代码>属性,您收到了异常。您可能正在寻找。欢迎您。考虑阅读。