我正在创建一个通用链表,并且必须创建两组数据。
第一个文件是“ auto.txt”,其中包含以下格式的汽车信息:
Brand Model Year
第二个文件是“ moto.txt”,其中包含以下格式的摩托车信息:
Brand Model Year Engine
我制作了一个双向链接列表,我需要制作两个列表,一个包含摩托车,另一个包含汽车。但是,出现以下错误:
cannot convert from 'L3_Console.Car' to 'T'
cannot convert from 'L3_Console.Motorcycle' to 'T'
这是我的代码:
class Program
{
static void Main(string[] args)
{
GenList<Car> Cars = Read<Car>("auto.txt");
GenList<Motorcycle> Motorcycles = Read<Motorcycle>("moto.txt");
}
public static GenList<T> Read<T>(string Failas)
{
GenList<T> List = new GenList<T>();
using (StreamReader reader = new StreamReader(File.Open(Failas, FileMode.Open), Encoding.GetEncoding(1257)))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
if (typeof(T) == typeof(Car)) List.Add(new Car(parts[0],parts[1],int.Parse(parts[2]))); //error here
else if (typeof(T) == typeof(Motorcycle)) List.Add(new Motorcycle(parts[0], parts[1], int.Parse(parts[2]),parts[3])); //error here
}
}
return List;
}
}
public sealed class GenList<T>
{
private sealed class Node<T>
{
public T Data { get; set; }
public Node<T> Previous { get; set; }
public Node<T> Next { get; set; }
public Node() { }
public Node(T data, Node<T> adr_p, Node<T> adr_n)
{
Data = data;
Previous = adr_p;
Next = adr_n;
}
}
private Node<T> start;
private Node<T> end;
private Node<T> current;
public GenList()
{
this.start = null;
this.end = null;
this.current = null;
}
public void Add(T data)
{
var dd = new Node<T>(data, null, start);
if (start != null)
start.Previous = dd;
else end = dd;
start = dd;
}
}
public class Car
{
public string Brand { get; private set; }
public string Model { get; private set; }
public int Year { get; private set; }
public Car(string brand, string model, int year)
{
Brand = brand;
Model = model;
Year = year;
}
}
public class Motorcycle
{
public string Brand { get; private set; }
public string Model { get; private set; }
public int Year { get; private set; }
public string Engine { get; private set; }
public Motorcycle(string brand, string model, int year,string engine)
{
Brand = brand;
Model = model;
Year = year;
Engine = engine;
}
}
如何正确地向列表中添加一个新节点,其中包含一个类,该类取决于函数的调用方式?谢谢