首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

C# -如何创建共享公共属性的不同类的数组?

在C#中,要创建具有共享公共属性的不同类的数组,可以使用父类和子类的继承关系。以下是一种实现方法:

  1. 首先,创建一个父类,该父类包含共享的公共属性。例如:
代码语言:csharp
复制
public class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }
}
  1. 然后,创建子类,这些子类继承自父类,并可以添加自己的特定属性。例如:
代码语言:csharp
复制
public class Dog : Animal
{
    public string Breed { get; set; }
}

public class Cat : Animal
{
    public bool IsIndoor { get; set; }
}
  1. 接下来,可以创建一个数组,该数组可以存储父类和子类的实例。例如:
代码语言:csharp
复制
Animal[] animals = new Animal[3];
animals[0] = new Dog { Name = "Buddy", Age = 3, Breed = "Labrador" };
animals[1] = new Cat { Name = "Whiskers", Age = 5, IsIndoor = true };
animals[2] = new Dog { Name = "Max", Age = 2, Breed = "Golden Retriever" };

在上面的示例中,我们创建了一个Animal类型的数组,并将其中的元素分别实例化为Dog和Cat类型的对象。由于Dog和Cat类都继承自Animal类,因此它们可以存储在Animal类型的数组中。

这样,我们就创建了一个具有共享公共属性的不同类的数组。可以通过遍历数组来访问每个对象的属性,例如:

代码语言:csharp
复制
foreach (Animal animal in animals)
{
    Console.WriteLine($"Name: {animal.Name}, Age: {animal.Age}");
    if (animal is Dog dog)
    {
        Console.WriteLine($"Breed: {dog.Breed}");
    }
    else if (animal is Cat cat)
    {
        Console.WriteLine($"Is Indoor: {cat.IsIndoor}");
    }
    Console.WriteLine();
}

上述代码将输出每个动物对象的名称和年龄,并根据对象的类型输出特定的属性(例如,狗的品种或猫是否室内猫)。

腾讯云相关产品和产品介绍链接地址:

请注意,以上链接仅供参考,具体产品选择应根据实际需求进行评估和决策。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券