c# 继承和向下继承层次结构

标签 c# inheritance

我想从现有的 A 类型对象创建一个 B 类型的新对象。B 继承自 A。我想确保 A 类型对象中的所有属性值都复制到该对象B 型。实现此目标的最佳方法是什么?

class A
{
     public int Foo{get; set;}
     public int Bar{get; set;}
}

class B : A
{
    public int Hello{get; set;}
}


class MyApp{
    public A getA(){
         return new A(){ Foo = 1, Bar = 3 };
    }

    public B getB(){
         A myA = getA();
         B myB = myA as B; //invalid, but this would be a very easy way to copy over the property values!
         myB.Hello = 5;
         return myB;
    }

    public B getBAlternative(){
         A myA = getA();
         B myB = new B();

         //copy over myA's property values to myB
         //is there a better way of doing the below, as it could get very tiresome for large numbers of properties
         myB.Foo = myA.Foo;
         myB.Bar = myA.Bar;

         myB.Hello = 5;
         return myB;
    }
}

最佳答案

class A {
    public int Foo { get; set; }
    public int Bar { get; set; }

    public A() { }

    public A(A a) {
        Foo = a.Foo;
        Bar = a.Bar;
    }
}

class B : A {
    public int Hello { get; set; }

    public B()
        : base() {

    }

    public B(A a)
        : base(a) {

    }
}

编辑

如果您不想复制每个属性,您可以使 A 和 B 可序列化并序列化 A 的实例(比如流,而不是文件)并用它初始化 B 的实例。但我警告你,这很恶心,而且开销很大:

A a = new A() {
    Bar = 1,
    Foo = 3
};

System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(A));
System.IO.Stream s = new System.IO.MemoryStream();
xs.Serialize(s, a);

string serial = System.Text.ASCIIEncoding.ASCII.GetString(ReadToEnd(s));
serial = serial.Replace("<A xmlns", "<B xmlns");
serial = serial.Replace("</A>", "</B>");

s.SetLength(0);
byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(serial);
s.Write(bytes, 0, bytes.Length);
s.Position = 0;

xs = new System.Xml.Serialization.XmlSerializer(typeof(B));
B b = xs.Deserialize(s) as B;

您可以在 ReadToEnd 上获得更多信息 here .

关于c# 继承和向下继承层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4815703/

相关文章:

c# - 是否可以获取从接口(interface)继承的每个类的实例?

java - 不允许多重继承时如何避免代码重复?

c# - .NET WCF 序列化问题

c# - MVC DropDownList 从一个数据库表填充并发送到另一个数据库表

C++: 错误: ‘class’ 没有名为的成员

java - Java中JVM如何加载父类

java - 转换为父类(super class)类型 a "Class"

c# - 如何使用正则表达式提取带引号的字符串?或者如何在 c# 中使用这个特定的正则表达式 ("[^"]*\.csv")?

c# - 在 C# 中使用命名空间

C#:在 C# 4.5 中等待请求完成