Let's assume I have a class Animal
and a subclass Dog
. The subclass Dog
has a property which the class Animal
doesn't have (let's assume the property is Age
and this property hasn't been defined in the Animal
class before).
Now when I have:
Animal animal;
and later I recognize that my animal is a dog:
animal = new Dog();
How can I access the age of the dog now like:
int age = animal.Age;
Thanks in advance!
You need to cast your animal
back to a Dog
to access the properties of it. You can do this safely with either:
as
with null
check:
Dog dog = animal as Dog; if (dog != null) { /*animal was Dog access properties here*/ }
is
with explicit cast:
if (animal is Dog) { Dog dog = (Dog)animal; }
However, this downcasting looks like a code smell, you might need to consider a redesign.
Simple cast it using (Dog)animal
.
In these cases I like to use the as
cast:
var probablyDog = animal as Dog;
if (probablyDog != null)
{
//indeed dog
probablyDog.Age;
}
if probablyDog
is null, it is no dog or animal
is null.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.