2012-10-24 57 views
0
public abstrct class Item 
{ 
    public string Name {get;set;} 
} 

public class Music : Item 
{ 
    public double Price {get;set;} 
} 

public class Game : Item 
{ 
    public string Image {get;set;} 
} 

public class Inventory 
{ 

private IList<Item> _games; 
private IList<Item> _musics; 

public Inventory() 
{ 
    _games = new List<Item>(); 
    _musics = new List<Item>(); 
} 

public void Add<T>(T item) where T : Item 
{ 
if(typeof(T) == typeof(Game)) 
{ 
    _game.add(item); 
} 
if(typeof(T) == typeof(Music)) 
{ 
    _muisc.add(item); 
} 


public List<T> GetCollection<T>() where T : Item 
{ 
    return (List<T>) _muiscs; 
} 

class Porgram 
{ 
    static void Main(string[] args) 
{ 
    Inventory inventory = new Inventory(); 
    var music1 = new Music(){ Name ="aa", Price = 10}; 
    var Music2 = new Music() { Name ="bb", price = 20 }; 

inventory.add(music1); 
inventory.add(music2); 


List<Music> myMusics = inventory.GetCollection<Music>(); 


} 

该代码将进行编译,但尝试调用Get Collection方法时会引发异常。为什么我不能施放?

我不确定为什么?我猜我使用通用不正确。

+0

你在哪里得到的错误? – IronMan84

+2

如何返回(列表)_muiscs;'编译?或'_muisc.add(item);'?或者'公共abstrct class Item'? –

+0

您的库存类应声明一个扩展Item的泛型类型。 – justderb

回答

2

列表<项目>不能转换成列表<音乐>。虽然Music是Item的子类,但泛型类型不遵循与其集合类型相同的继承模式。修复代码最简单的方法是将GetCollection方法中的强制转换为对Linq扩展方法cast的调用,然后是ToList。也就是说,我认为你的整个班级都可以重新设计,以更好地处理这种继承。

所以,你GetCollection方法是这样的:

public List<T> GetCollection<T>() where T : Item 
{ 
    return _musics.Cast<T>().ToList(); 
} 
0

试试这个代码:

public abstract class Item 
{ 
    public string Name { get; set; } 
} 

public class Music : Item 
{ 
    public double Price { get; set; } 
} 

public class Game : Item 
{ 
    public string Image { get; set; } 
} 

public class Inventory<E> where E : Item 
{ 

    private IList<E> _games; 
    private IList<E> _musics; 

    public Inventory() 
    { 
     _games = new List<E>(); 
     _musics = new List<E>(); 
    } 

    public void Add(E item) 
    { 
     if (typeof(E) == typeof(Game)) 
     { 
      _games.Add(item); 
     } 
     if (typeof(E) == typeof(Music)) 
     { 
      _musics.Add(item); 
     } 
    } 


    public List<E> GetCollection() 
    { 
     return _musics; 
    } 
} 

public class Program 
{ 
    public static void Main(string[] args) 
    { 
     Inventory<Item> inventory = new Inventory<Item>(); 
     var music1 = new Music() { Name = "aa", Price = 10 }; 
     var music2 = new Music() { Name = "bb", Price = 20 }; 

     inventory.Add(music1); 
     inventory.Add(music2); 


     List<Item> myMusics = inventory.GetCollection(); 


    } 
} 

您必须声明你的库存类是通用的,其中需要在还扩展Item

类:看起来你写的代码,并且没我不知道你为什么这样做...

+0

<可怕的想法>我的猜测是这是一个混淆他在生产系统中得到的东西的尝试。

0

只需修改GetCollection方法

public List <T> GetCollection<T>() where T :Item 
     { 

      if (typeof(T) == typeof(Game)) 
      { 
       return _games.Cast<T>().ToList(); 
      } 
      if (typeof(T) == typeof(Music)) 
      { 
       return _musics.Cast<T>().ToList(); ; 
      } 
     return null; 
     }