C#继承。从基类派生类 [英] C# inheritance. Derived class from Base class
问题描述
我有一个基类
public class A
{
public string s1;
public string s2;
}
我也有一个派生类:
I also have a derived class :
public class B : A
{
public string s3;
}
假设我的程序中创建A类的一个实例。
Suppose my program created an instance of class A.
A aClassInstance = new A();
一些参数设置:
some parameters were set:
aClassInstance.s1 = "string 1";
aClassInstance.s2 = "string 2";
在这一点上我想创建B类的一个实例,但我想B到已经。有我的A类实例的值
At this point I would like to create an instance of class B. But I would like B to already have the values of my instance of class A.
这不工作:
public B bClassInstance = new B():
bClassInstance = (B)aClassInstance;
也不是这:
NEITHER DID THIS:
发了。类中的clone方法
Made a clone method within Class A.
public B cloneA() {
A a = new A();
a = (A)this.MemberwiseClone()
return(B)a;
}
的
VS代码采用两种以上 - 但我得到运行时错误
The VS code takes both of the above - but I get run-time errors
请帮忙
推荐答案
你有基本的问题是,你必须构造型 B
的一个实例(包含事业类型的属性 A
)。你的方法克隆 A
实例将无法正常工作,因为这样可以给你键入 A
的一个实例,你不能转换为 b
。
The base problem you have is, that you have to construct an instance of type B
(which contains of cause the properties of type A
). Your approach to clone an A
instance won't work, because that gives you an instance of type A
, which you can't convert to B
.
我会写的类和b类的构造函数这需要类型的参数A. b类的构造函数只是传递价值,以它的基类A. A类的构造函数知道如何领域复制到其自身:
I would write constructors for class A and B which takes a parameter of type A. The constructor of class B just passes the value to its base class A. The constructor of class A knows how to copy the fields to itself:
class A {
public A(A copyMe) {
s1 = copyMe.s1;
...
}
class B : A {
public B(A aInstance) : base(aInstance) {
}
}
使用这种方式:
A a = new A();
a.s1 = "...";
B b = new B(a);
修改
当你不希望有添加新字段或道具时改变 A
的构造函数,你可以使用反射来复制属性。要么使用自定义属性来装点你想要的复制,或复制的 A
刚才的所有道具/字段:
When you don't want to have to change the constructor of A
when adding new fields or props, you could use reflection to copy the properties. Either use a custom attribute to decorate what you want to copy, or copy just all props/fields of A
:
public A (A copyMe) {
Type t = copyMe.GetType();
foreach (FieldInfo fieldInf in t.GetFields())
{
fieldInf.SetValue(this, fieldInf.GetValue(copyMe));
}
foreach (PropertyInfo propInf in t.GetProperties())
{
propInf.SetValue(this, propInf.GetValue(copyMe));
}
}
我没有带试过代码,但关键应该变得清晰起来。
I havn't tried the code, but the point should become clear.
这篇关于C#继承。从基类派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!