Creating cat and dog objects and adding them to collection without repeating base class properties
I am populating a collection List from data from a database. The database results contain both cats and dogs.
I want to do something like this
var animals = new List();
var animal = new Animal()
animal.Name = row["name"] //Name is a property in the base class Animal (shared by both cats and dogs)
if row["type"] == 1 //cat
animal = (Cat)animal;
animal.CanMeow = row["meow"]; // set property specific to cats
else
animal = (Dog)animal;
animal.Bark = row["bark"]; // set property specific to dogs
end if
animals.Add(animal);
How can I a开发者_高级运维ccomplish this in c# .net 4?
ty
You're doing it the wrong way. You are creating an Animal
and trying to cast that to a derived class. That's not possible. You need to create an instance of the derived class and cast it to the base class.
List list = new List<Animal>();
Animal a = null;
if(row["type"]==1)
{
Cat c = new Cat();
a = (Animal)c;
//cat specific assignments here
c.CanMeow = row["CanMeow"];
}
else
{
Dog d = new Dog();
a = (Animal)d;
//dog specific assignments here
}
//generic assignments here
a.Name=row["Name"]
list.Add(a);
I would use a scheme like this
private void PopulateAnimal(animal a, DataRow dr)
{
animal.Name = row[NAME];
}
private void Something()
{
//Read DB
if (row[TYPE] == CAT){
Cat c = new Cat();
PopulateAnimal(c, row);
//Cat properties
c.CanMeow = row[CAN_MEOW];
animals.Add(c);
}else if (row[TYPE] == DOG){
Dog d = new Dog();
PopulateAnimal(d, row);
//Dog properties
d.CanBark = row[CAN_BARK];
animals.Add(d);
}else{
//throw or whatever
}
}
This allows you to put all the common property assignments in a single method and lets you call it from wherever its needed.
If you like you can move the animals.Add
call to the PopulateAnimal
method (and call it last). This might me a little less code, but a little less clear as well.
Syntax might be a bit off but here it goes:
List<Animal> animals = new List<Animal>();
var cats = from animal in animalTable.AsEnumerable()
where animal.Field<int>("type") == 1
select new Cat() { Name = animal.Field<string>("name"), CanMeow = animal.Field<bool>("meow") };
var dogs = from animal in animalTable.AsEnumerable()
where animal.Field<int>("type") != 1
select new Dpg() { Name = animal.Field<string>("name"), Bark = animal.Field<bool>("bark") };
animals.addRange(cats);
animals.addRange(dogs);
精彩评论