0

say I have these classes:

public class Animal
{

}

public class Elephant : Animal
{
  public string Name { get; set; }
}

and I have a controller method

    public SubmitElephants()
{
    var elephants = new List<Animal>();

    elephants.Add(new Elephant { Name = "Timmy" };
    elephants.Add(new Elephant { Name = "Michael" };

return View("DisplayElephants", elephants);

}

The DisplayElephants view looks like:

@model IList<Elephant>

@foreach(var elephant in Model)
{
  <div>@elephant.Name</div>
}

So if I run this code I will get the error:

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[Animal]', but this dictionary requires a model item of type 'System.Collections.Generic.IList1[Elephant]'

So no I'm NOT wanting to change my list to be var elephants = new List<Elephant>();

What I'm wanting to know given I have a list of Animals that I know contains only Elephants how can I from the controller pass this to a view which is specific to Elephants?

4

2 回答 2

1

AFAIK 这是不可能的。从某种意义上说,您正在尝试的与协方差相反。

本文介绍协方差和逆变。

总之,你可以这样做 -

IEnumerable<Elephant> elephants = new List<Elephant>();
IEnumerable<Animal> animals = elephants;

你实际上想要相反的方式。

另请注意,并非所有通用集合都是协变的。这篇文章告诉我们在 C# 中协变的集合。

于 2013-04-23T01:21:16.370 回答
0

更改此行:

var elephants = new List<Animal>();

至:

var elephants = new List<Elephant>();

有关为什么会这样的更多信息,请参阅@Srikanth 的回答。

于 2013-04-23T01:45:56.983 回答