C# inheritance. Derived class from Base class

后端 未结 4 2007
一生所求
一生所求 2020-12-15 06:28

I have a base class

public class A   
{
    public string s1;
    public string s2;
}

I also have a derived class :

public         


        
4条回答
  •  我在风中等你
    2020-12-15 06:42

    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.

    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) {
        }
    
    }
    

    Use it this way:

    A a = new A();
    a.s1 = "...";
    
    B b = new B(a);
    

    EDIT

    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.

提交回复
热议问题