为什么我无法添加List <t>是否归因于Bark?

时间:2018-04-04 06:09:43

标签: c# generics

处理编码问题时,我需要使用通用列表而不是数组,但是很难弄清楚为什么它不会允许我添加通用列表 我有一个抽象的基类,我的其他类继承。

public abstract class Pet
{
    public string Name {get;set;}
    public Pet(string name)
    {
        this.Name=name;
    }
    public void Eat()
    {
        Console.WriteLine(String.Format("{0}: nom nom nom", Name));
    }
}

public class Dog: Pet
{
    public Dog(string name):base(name)
    {

    }

    public void Bark()
    {
        Console.WriteLine(String.Format("{0}: bark", Name));
    }
}

最后我有一个program.cs文件,其中包含以下内容。

public static void Main(String[] args)
{
    Dog lassie = new Dog("Lassie");
    Dog benji = new Dog("Benji");
    Dog oddie = new Dog("Oddie");

    Cat garfield = new Cat("Garfield");
    Cat tony = new Cat("Tony");
    Cat felix = new Cat("Felix");

    Dog[] dogs = { lassie, benji, oddie };
    List<string> dogList = new List<string>();
    dogList.Add("Lassie");
    dogList.Add("Benji");
    dogList.Add("Oddie");

    List<string> catList = new List<string>();
    catList.Add("Garfield");
    catList.Add("Tony");
    catList.Add("Felix");

    Cat[] cats = { garfield, tony, felix };
    Pet[] pets = { garfield, lassie, tony, benji, oddie, felix };

    Bark(dogList);
    Meow(cats);
    Feed(pets);

    Call(pets);

    ListCatsThenDogsInAlphabeticalOrder(pets);

    Console.WriteLine("Done");
    Console.ReadLine();
}

private static void MakeAList(Dog[] dogs)
{
    List<string> dogList = new List<string>();
    for (int i=0;i < dogs.Length; i++)
    {
        dogList.Add(dogs[i]);

    }
}

private static void Bark(Dog[] dogs)
{
    foreach (Dog dog in dogs)
        dog.Bark();
}

private static void Meow(Cat[] cats)
{
    foreach (Cat cat in cats)
        cat.Meow();
}

private static void Feed(Pet[] animals)
{
    foreach (Pet animal in animals)
        animal.Eat();
}

/// <summary>
///   Calls a pet.  The pet should respond by barking or meowing as appropriate.
/// </summary>
/// 
/// <param name="pets">
///   A list of pets.  Not null and contains no nulls.
/// </param>

private static void Call(Pet[] pets)
{
    foreach (Cat cat in pets)
    {
        Console.WriteLine("Come here " + cat.Name);
        cat.Meow();
    }

    foreach (Dog dog in pets)
    {
        Console.WriteLine("Come here " + dog.Name);
        dog.Bark();
    }
}

private static void ListCatsThenDogsInAlphabeticalOrder(Pet[] pets)
{
    Console.WriteLine("\nPets");
    Console.WriteLine("----------");

    // Use a linq expression or extension methods to sort the pets first by type (cats first, dogs second),
    // and then by alphabetically by their names.  Print the sorted list.

    foreach (Pet pet in pets)

        Console.WriteLine(pet.Name);

    Console.WriteLine("----------");
}

我遇到的问题是,由于树皮方法,我似乎不想尝试制作List<string> dogList,而不确定如何修复它。我完全坚持如何使其发挥作用,对Bark(dogList)的调用失败了:

  

Argument1:无法从System.Collections.Generic.List转换   到Problem4.Dog []

4 个答案:

答案 0 :(得分:1)

这也是您的代码问题,您正在创建字符串列表并在方法中创建字符串列表,该方法期待您定义的Pets类型列表。

   List<string> dogList = new List<string>();
    dogList.Add("Lassie");
    dogList.Add("Benji");
    dogList.Add("Oddie");
    //Bark(dogList);this is not going to work as you are passing string array

应该是

   List<Dog> dogList = new List<Dog>();
    dogList.Add(new Dog("Lassie"));
    dogList.Add(new Dog("Benji"));
    dogList.Add(new Dog("Oddie"));
    Bark(dogList);

   private static void Bark(IEnumerable<Dog> dogs)
   {
     foreach (Dog dog in dogs)
        dog.Bark();
   }

同样适用于catlist,它也会起作用。

解决问题的最佳方法是将其设为IEnumerable<T>,因此代码将为

用户IEnumerable这将同时处理Array and List

    static void Call(IEnumerable<Pet> pets)
    {

    } 

注意:我在您使用IEnumerable时建议foreachIndex无法访问元素,如果您想要Index基本访问权限,请使用IList cat 1}}

要支持dogIBark的树皮方法,请创建新接口 interface IBark { void Bark(); } public class Dog:Pet,IBark { public Dog(string name):base(name) {} public void Bark() { Console.WriteLine(String.Format("{0}: bark", Name)); } } //do same changes with cat 并按以下方式实现,并更改树皮方法,如下所示

   static void Call(IEnumerable<IBark> pets)
   {
    foreach (IBark pet in pets)
        pet.Bark();
   }

所以在主类中它就像

 jQuery(document).ready(function($) {

 if ($('body').hasClass('post-template-default')) {
    if(screen.width <= 991) {
        setTimeout(function(){ 
              swal({
        type: 'info',
        title: 'You can swipe!',
        text: 'Swipe to Right or Left to navigate through posts.',
        showConfirmButton: 'false',}) },1000); // alert }}});   

答案 1 :(得分:1)

我可以看到几个错误:

方法 MakeAList 应如下所示:

private static List<string> MakeAList(Dog[] dogs)
{
    List<string> dogList = new List<string>();
    for (int i = 0; i < dogs.Length; i++)
    {
        dogList.Add(dogs[i].Name);
    }
    return dogList;
}

您需要设置名称,您无法设置对象,因为如果不是,则应该是 狗列表 不是 字符串列表

如果您需要狗列表,则不能使用字符串列表

List<Dog> dogList = new List<Dog>();
dogList.Add(new Dog("Lassie"));
dogList.Add(new Dog("Benji"));
dogList.Add(new Dog("Oddie"));

最后,作为传递List的传递时,您可以使用LINQ进行转换:

Bark(dogList.ToArray());
Meow(cats.ToArray());
Feed(pets.ToArray());

一些建议,不要将 数组列表混合,这会影响项目的效果。

答案 2 :(得分:1)

Cats & Dogs (test it online)

类定义(根据我对Pranay Rana's answer的评论):

public abstract class Pet
{    
    public string Name {get;set;}
    public Pet(string name)
    {
        this.Name=name;
    }
    public void Eat()
    {
        Console.WriteLine(String.Format("{0}: nom nom nom", Name));
    }
    public abstract void Speak();
}

public class Dog: Pet
{
    public Dog(string name):base(name){}

    public override void Speak()
    {
        Bark();
    }
    public void Bark()
    {
        Console.WriteLine(String.Format("{0}: bark", Name));
    }
}

public class Cat: Pet
{
    public Cat(string name):base(name){}

    public override void Speak()
    {
        Meow();
    }
    public void Meow()
    {
        Console.WriteLine(String.Format("{0}: meow", Name));
    }
}

然后您可以使用以下内容来呼叫和列出宠物:

class Program
{
    static void Main()
    {
        List<Pet> Pets = new List<Pet>();    
        Pets.Add(new Dog("Lassie"));
        Pets.Add(new Cat("Garfield"));
        Pets.Add(new Dog("Benji"));
        Pets.Add(new Cat("Tony"));
        Pets.Add(new Dog("Oddie"));
        Pets.Add(new Cat("Felix"));

        Call(Pets);

        Console.WriteLine();

        ListCatsThenDogs(Pets);
    }

    static void Call(IEnumerable<Pet> Pets)
    {
        Console.WriteLine("Calling all pets...");

        foreach (Pet pet in Pets)
        {
            Console.WriteLine("Come here " + pet.Name);
            pet.Speak(); // using the abstract Speak() method
        }
    }

    static void ListCatsThenDogs(IEnumerable<Pet> Pets)
    {
        Console.WriteLine("Listing cats then dogs in alphabetical order...");

        foreach(Pet pet in Pets
            .OrderBy(p => p.GetType().FullName) // order by type ("Cat" < "Dog")
            .ThenBy(p => p.Name))               // then by name
        {
            Console.WriteLine(pet.Name);
        }
    }
}

答案 3 :(得分:0)

您无法将List<T>作为数组T[]传递。

改为使用Bark(dogs)

但是,您可以将数组T[]作为IList<T>传递。大多数情况下,您会使用IEnumerable<T>作为参数。您可以将这些数组和列表作为IEnumerable<T>传递。