【问题标题】:C# Class Add ID from one class to anotherC# 类将 ID 从一个类添加到另一个类
【发布时间】:2016-04-19 08:30:40
【问题描述】:

我有一个以 Animal 命名的类,具有名称、类型、性别,我还有另一个以 AnimalList 命名的类,我需要知道如何将动物添加到我的 AnimalList,这是我的类动物(我在控制台应用程序中): 文件名 Animal.cs

class Animal
{
  public string Name {get; set;}
  public string Type {get; set;}
  public string Gender {get; set;}

  public Person(string name, string type, string gender)
  {
       Name = name;
       Type = type;
       Gender = gender;
  }
}

还有我的班级 AnimalList: 文件名AnimalList.cs

class AnimalList: List<Animal>
{
     what should i do to add Animals to this list
}

不应该这样更好吗?

public new void Add(Animal value)
{
}

【问题讨论】:

标签: c#


【解决方案1】:

为什么你的Animal 类中有Person 的构造函数?

这样做:

var animals = new AnimalList();
var animal = new Animal();
animals.Add(animal);

你必须公开你的 Animal 类:

public class Animal
{
}

【讨论】:

    【解决方案2】:

    在某处(例如在 main 方法中)实例化您的 AnimalList 类,然后添加 Animal 类的实例。

    例如:

    var animals = new AnimalList();
    
    animals.Add(new Animal() {
       Name = "", 
       Type = "", 
       Gender = ""});
    

    【讨论】:

    • 检查 animalListanimals fyi :)
    • 您应该将animalList 重命名为animals,反之亦然。此外,您的代码不是有效的 C# 代码。
    【解决方案3】:

    首先将您的课程设为公开 然后这样做:

     AnimalList animalList = new AnimalList();
                Animal animal = new Animal();
                animal.Name = "x";
                animal.Type = "Y";
                animal.Gender = "M/F";
                animalList.add(animal);
    

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 1970-01-01
      • 2012-02-17
      • 2013-02-10
      • 2023-03-26
      • 2020-02-26
      • 2014-08-13
      • 2013-10-30
      • 2021-12-20
      相关资源
      最近更新 更多