Initialize base class in .NET

2019-04-06 09:36发布

How do I go about if I need to initialize an object's base with existing object? For example, in this scenario:

public class A
{
    public string field1;
    public string field2;
}

public class B : A
{
    public string field3;
    public void Assign(A source)
    {
        this.base = source; // <-- will not work, what can I do here?
    }
}

Assign() method can, obviously assign values to the base class field-by-field, but isn't there a better solution? Since class B inherits from A, there must be a way to just assign A to the B.base

In C++ this would be a trivial thing to do, but I can't seem to grasp how to do this in .NET

标签: c# .net oop
10条回答
何必那么认真
2楼-- · 2019-04-06 10:31

According to MSDN, "base" can inly be used for the following operations:

  • Call a method on the base class that has been overridden by another method.
  • Specify which base-class constructor should be called when creating instances of the derived class.
查看更多
放我归山
3楼-- · 2019-04-06 10:39
        public Assign(A a)
        {
            foreach (var prop in typeof(A).GetProperties())
            {
                this.GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue(a, null),null);
            }
        }

Basically, it uses reflection to get all the properties of the base and assign the values of this, to all the values that exist in A.

EDIT: To all you naysayers out there, I quickly tested this now with a base class that had 100 integer variables. I then had this assign method in a subclass. It took 46 milliseconds to run. I don't know about you, but I'm totally fine with that.

查看更多
迷人小祖宗
4楼-- · 2019-04-06 10:39

I hope I'm not the only one who thinks swapping out your base class is a bad design pattern. Another approach is to replace inheritance with composition:

public class A
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

public class B
{
    public A A { get; set; }
    public string Field3 { get; set; }

    public B(A a) { this.A = a; }
}

Now its trivial to write something like this:

B b = new B ( new A { Field1 = "hello", Field2 = "world" } );

b.A = new A { Field1 = "hola", Field2 = "luna" };
查看更多
forever°为你锁心
5楼-- · 2019-04-06 10:40

While there are many excellent answers here, I think the proper way to do this is by chaining the constructors:

public class A
{
    public string field1;
    public string field2;

    public A(string field1, string2 field2)
    {
         this.field1 = field1;
         this.field2 = field2;
    }
}

public class B : A
{
    public string field3;

    public B(string field1, string2 field2, string field3)
        : base(field1, field2)
    {
        this.field3 = field3;
    }
}
查看更多
登录 后发表回答