2013-05-10 68 views
0

我遇到了一个我从未见过的错误。我希望有人能提供帮助。错误7,参数1:无法从''转换为''

这里是我的代码:

public class MyT 
{ 
    public int ID { get; set; } 
    public MyT Set(string Line) 
    { 
     int x = 0; 

     this.ID = Convert.ToInt32(Line); 

     return this; 
    } 
} 

public class MyList<T> : List<T> where T : MyT, new() 
{ 
    internal T Add(T n) 
    { 
     Read(); 
     Add(n); 
     return n; 
    } 
    internal MyList<T> Read() 
    { 
     Clear(); 
     StreamReader sr = new StreamReader(@"../../Files/" + GetType().Name + ".txt"); 
     while (!sr.EndOfStream) 
      Add(new T().Set(sr.ReadLine())); //<----Here is my error! 
     sr.Close(); 
     return this; 
    } 
} 

public class Customer : MyT 
{ 
    public int ID { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

public class Item : MyT 
{ 
    public int ID { get; set; } 
    public string Category { get; set; } 
    public string Name { get; set; } 
    public double Price { get; set; } 
} 

public class MyClass 
{ 
    MyList<Customer> Customers = new MyList<Customer>(); 
    MyList<Item> Items = new MyList<Item>(); 
} 

在那说,该行 “添加(新T()设置(sr.ReadLine()));”我得到“Error 7,参数1:无法从'Simple_Reservation_System.MyT'转换为'T'”。有人可以帮我解决这个问题。

+0

坦率地说,这是不是很“普通”,你为什么不只是使用列表 MYLIST里面? – 2013-05-10 07:35:41

回答

0

您的类型MyList只能包含“T”类型的元素(声明列表时指定)。您尝试添加的元素是“MyT”类型,不能缩减为“T”。

考虑MyList与MyT的另一个子类型MyOtherT一起声明的情况。不可能将MyT投射到MyOtherT。

+0

你能举个例子吗? – Makai 2013-05-10 07:58:08

+0

您的代码中有一个示例:class Customer来自MyT。因此,为了说明错误:在问题行上,您将尝试投射“MyT”类型的对象以键入“客户”,这是不允许的。您始终可以投射到超类型,但从不投射到子类型。 – Andreas 2013-05-10 08:49:22

+0

我明白了。现在我该如何解决它? – Makai 2013-05-10 09:14:45

0

您的添加参数采用泛型类型T.您的设置方法返回具体类MyT。即使你把这个它不等于T.事实上:

添加(新MYT())

它会返回一个错误。

我还想补充说,这只是在MyList类中出现错误。如果你从不同的类调用相同的方法,它将起作用。

0

因为您的类型MyT与通用参数T不一样。当您编写new T()时,将创建一个类型为T的实例,该实例必须从MyT继承,但这不一定是MyT的类型。看下面这个例子,看看我的意思是:

public class MyT1 : MyT 
{ 

} 
//You list can contains only type of MyT1 
var myList = new MyList<MyT1>(); 

var myT1 = new MyT1(); 
//And you try to add the type MyT to this list. 
MyT myT = myT1.Set("someValue"); 
//And here you get the error, because MyT is not the same that MyT1. 
myList.Add(myT); 
+0

好的。那么我该如何解决它? – Makai 2013-05-10 07:50:06

+0

我不知道你的任务的细节。例如,你可以从'List '继承你的'MyList'类,然后你的类将不是通用的。但是,如果您创建一个负责读取文件并返回'List '的实例的类,那将会更好。 – 2013-05-10 07:59:08

相关问题