C# inheritance. Derived class from Base class

后端 未结 4 1994
一生所求
一生所求 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:55

    After playing around and reading everything I could get my eyes on, both of the above solutions by GvS and Jan work. However, the end result that I wanted to achieve is not to be forced to write out each member in the Copy methods.

    Why: a) If the class is edited and another object is added, the copy method will have to be updated. If someone else updates the class, they may forget to do this.

    b) There may be a lot of members, and assigning them may be time consuming.

    c) It just doesn't "feel" right. (Probably because I am very lazy).

    Fortunately, I am not the only one with the same thoughts. Found a very very easy solution via the ValueInjector. (it has been discussed on these boards a lot).

    After getting the dll (http://valueinjecter.codeplex.com/documentation)

    The code becomes:

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

    That's it :)

    Obviously you would have to include:

    using Omu.ValueInjecter;
    

    And not forget to add it to the references.

提交回复
热议问题