C# 为什么可以';添加列表<;T>;是因为树皮吗?

C# 为什么可以';添加列表<;T>;是因为树皮吗?,c#,generics,C#,Generics,在处理一个编码问题时,我需要使用一个泛型列表而不是数组来处理这个问题,但是我很难弄清楚为什么它不允许我添加泛型列表 我有一个抽象基类,我的其他类从中继承 public abstract class Pet { public string Name {get;set;} public Pet(string name) { this.Name=name; } public void Eat() { Console.Wri

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

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("----------");
}
publicstaticvoidmain(字符串[]args)
{
狗拉西=新狗(“拉西”);
狗本吉=新狗(“本吉”);
狗奥迪=新狗(“奥迪”);
猫加菲猫=新猫(“加菲猫”);
猫托尼=新猫(“托尼”);
猫菲利克斯=新猫(“菲利克斯”);
狗[]狗={lassie,benji,oddie};
List dogList=新列表();
添加(“Lassie”);
添加(“本吉”);
添加(“古怪”);
List catList=新列表();
catList.添加(“加菲猫”);
catList.添加(“托尼”);
catList.添加(“Felix”);
猫[]猫={garfield,tony,felix};
宠物[]宠物={garfield,lassie,tony,benji,oddie,felix};
树皮(狗名单);
喵喵(猫);
饲料(宠物);
呼叫(宠物);

名单中的宠物(宠物); 控制台。写入线(“完成”); Console.ReadLine(); } 私有静态无效生成列表(狗[]狗) { List dogList=新列表(); 对于(int i=0;i私有静态无效列表CatsEndogsinalphabeticalorder(Pet[]pets) { Console.WriteLine(“\nPets”); Console.WriteLine(--------------”; //使用linq表达式或扩展方法首先按类型对宠物进行排序(猫优先,狗其次), //然后按姓名的字母顺序打印排序后的列表。 foreach(宠物中的宠物) 控制台写入线(宠物名称); Console.WriteLine(--------------”; }
我遇到的问题是,由于bark方法,它似乎不喜欢我尝试制作一个
列表dogList
,不知道如何修复它。我一直在思考如何让它工作,调用
Bark(dogList)
失败的原因是:

Argument1:无法从System.Collections.Generic.List转换 解决问题4.狗


不能将
列表作为数组
T[]
传递

使用
吠叫(狗)
代替


但是,可以将数组
T[]
作为
IList
传递。通常,您会使用
IEnumerable
作为参数。可以将数组和列表作为
IEnumerable
传递。不能将
列表作为数组
T[]
传递

使用
吠叫(狗)
代替


但是,可以将数组
T[]
作为
IList
传递。通常,您会使用
IEnumerable
作为参数。您可以将数组和列表传递为
IEnumerable

这也是代码的问题,您正在创建字符串列表,并在方法中传递字符串列表,该方法需要您定义的
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
注意:我建议
IEnumerable
当您使用
foreach
时,不能通过
Index
访问元素,如果您想要
Index
基本访问,请使用
IList


要支持猫和狗的吠叫方法,请创建新的接口
IBark
,并按如下所示实现它,还可以按如下所示更改吠叫方法

   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();
   }
静态无效调用(IEnumerable)
{
foreach(宠物中的IBark宠物)
宠物树皮();
}


这也是您的代码的问题,您正在创建字符串列表,并在方法中传递字符串列表,该方法需要您定义的
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
注意:我建议
IEnumerable
当您使用
foreach
时,不能通过
Index
访问元素,如果您想要
Index
基本访问,请使用
IList


要支持猫和狗的吠叫方法,请创建新的接口
IBark
,并按如下所示实现它,还可以按如下所示更改吠叫方法

   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();
   }
静态无效调用(IEnumerable)
{
foreach(宠物中的IBark宠物)
宠物树皮();
}


我可以看到几个错误:

方法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;
}

一些建议,不要将数组与列表混用,这将影响项目的性能。

我可以看到一些错误:

方法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;
}
一些建议,不要将数组与列表混用,这将影响项目的性能。

课程定义(根据我的评论):

然后,您可以使用以下命令呼叫并列出宠物:

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);
        }
    }
}
类程序
{
静态void Main()
{
列表宠物=新列表();
宠物。添加(新狗(“小姑娘”);
宠物。添加(新猫(“加菲猫”);
宠物。添加(新狗(“本吉”);
宠物。添加(新猫(“托尼”));
宠物。添加(新狗(“古怪”);
宠物。添加(新猫(“菲利克斯”);
呼叫(宠物);
Console.WriteLine();
列表项(
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);
        }
    }
}