在C#中,要创建具有共享公共属性的不同类的数组,可以使用父类和子类的继承关系。以下是一种实现方法:
public class Animal
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Dog : Animal
{
public string Breed { get; set; }
}
public class Cat : Animal
{
public bool IsIndoor { get; set; }
}
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类型的数组中。
这样,我们就创建了一个具有共享公共属性的不同类的数组。可以通过遍历数组来访问每个对象的属性,例如:
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();
}
上述代码将输出每个动物对象的名称和年龄,并根据对象的类型输出特定的属性(例如,狗的品种或猫是否室内猫)。
腾讯云相关产品和产品介绍链接地址:
请注意,以上链接仅供参考,具体产品选择应根据实际需求进行评估和决策。
领取专属 10元无门槛券
手把手带您无忧上云