To facilitate the presentation, where a total of two simple classes
parent class: class Animal (Animal)
/// <summary>
/// 动物类-父类
/// </summary>
public class Animal
{
/// <summary>
/// 脚
/// </summary>
public string Foot { get; set; }
/// <summary>
/// 头
/// </summary>
public string Head { get; set; }
}
Subclass: dogs (Dog)
/// <summary>
/// 狗类-继承动物类
/// </summary>
public class Dog : Animal
{
/// <summary>
/// 尾巴
/// </summary>
public string Tail { get; set; }
/// <summary>
/// 构造函数
/// </summary>
public Dog()
{
Head = "狗头";
Foot = "狗腿";
Tail = "狗尾巴";
}
}
|
The first step: If we convert the class Dog Animal class
Dog dog = new Dog();
//转换为动物类---子类转换为父类
Animal animal = dog as Animal;
We always follow this idea should be extended attributes is discarded subclass (here Tail), leaving only the parent class attributes (Foot, Head). Then the result of the conversion Animal class should this
second step: If we continue to re-convert the object class Dog Dog dog2 = animal as Dog;
Dog class should be like this
, but in fact, in the first step to Dog
convert Animal
the time, Animal
did not put Tail
this field throwing go, as shown below
, however, IntelliSense in VS and we can not access the Tail
property directly using the compiler also being given
and from the above results, we can guess the actual results of the second step, Dog
the class Tail
is not the NULL
third step : try parent class to a subclass
obviously, the parent and can not be converted into sub-categories, although the compiler can, but will throw runtime System.InvalidCastException
exceptions, of course, use this as
keyword to avoid this anomaly, the result is returned NULL
then the parent class how convert it into sub-classes? For some relatively simple class, we can individually assign by traversing the way
Animal animal = new Animal
{
Foot = "脚",
Head = "头"
};
Dog dog = new Dog
{
Foot = animal.Foot,
Head = animal.Head,
};
If multiple properties when using this method is in trouble, then you can use the 反射
traversal attribute set to a value corresponding to
Animal animal = new Animal
{
Foot = "脚",
Head = "头"
};
Dog dog = new Dog();
//遍历Animal类的公共属性
foreach (PropertyInfo item in typeof(Animal).GetProperties())
{
item.SetValue(dog, item.GetValue(animal));
}
result:
More about the reflection can refer to the official documentation
To this conclusion should be clear
- Subclasses can convert parent class and subclass of the extended attribute is the parent class 'recessive' retention, but not accessible to the parent class back to a subclass.
- The parent can not be converted to a subclass, where it touches well understood, after all, less can be varied, less variable and more to die. Of course, if the parent class into subclasses want extra attributes are set to default
NULL
is unreasonable, because the value type (eg: int) can not be setNULL