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 :(得分:2)
列表&lt;项目&gt;无法转换为列表&lt; Music&gt;。虽然Music是Item的子类,但泛型类型不遵循与其集合类型相同的继承模式。修复代码的最简单方法是使用对Linq扩展方法强制转换的调用替换GetCollection方法中的强制转换,然后是ToList。也就是说,我认为你的整个课程可以重新设计,以更好地处理这种遗产。
因此,您的GetCollection方法如下所示:
public List<T> GetCollection<T>() where T : Item
{
return _musics.Cast<T>().ToList();
}
答案 1 :(得分: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();
}
}
您需要将Inventory类声明为扩展Item
另外:看起来你编写了代码,并没有复制并粘贴它......我不知道你为什么这么做......
答案 2 :(得分: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;
}