2013-05-10 80 views
0

我想自定义列表。我主要是想通了,但我遇到了一个问题。这里是我一起工作的代码:如何自定义列表<T>?

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>(); 
} 

在代码中,你可以看到,我想创建一个自定义列表。 在这里,您还可以看到我拥有的许多课程中的两个。所有的课程都有一个ID。 所有类都与自定义列表匹配。 这个问题似乎在MyList<T>.Read() - Add(new T().Set(sr.ReadLine())); 最后,我得到MyT不能转换为T.我需要知道如何解决它。

+0

扩展方法很可能是除非子类对您真的很重要,否则会更好。 – 2013-05-10 09:51:01

+5

'T:MyT'如果T只能是MyT,为什么要使用泛型? – I4V 2013-05-10 09:52:57

+1

I4V:它使用编译为MyT的通用版本,而不是仅使用内部对象的非泛型,这可能由于投射而变慢;并且可以有MyT的子类... – 2013-05-10 10:00:50

回答

1

Set方法返回类型MyT而不是特定的类型。使通用的,所以它可以返回的特定类型:

public T Set<T>(string Line) where T : MyT { 
    int x = 0; 
    this.ID = Convert.ToInt32(Line); 
    return (T)this; 
} 

用法:

Add(new T().Set<T>(sr.ReadLine())); 

或铸参考回到特定类型:

Add((T)(new T().Set(sr.ReadLine()))); 
+0

我尝试了你的建议。你给的第一个用法仍然给出与以前完全相同的错误。第二个提供了一个新的错误。 _Error 6:方法'MyT.Set (字符串)'的类型参数不能从用法推断。 “我不知道这意味着什么。”# – Makai 2013-05-10 19:08:14

+0

@Makai:对不起,该方法当然应该有返回类型'T',而不是'MyT'。当你从第二个代码,这意味着您修改了第一个示例中的方法,并尝试像第二个示例中那样使用它。 – Guffa 2013-05-10 21:06:14