开发者

inheritance in c#. copy properties in the base object

I have an object (A) with many properties. I make a new object B that extends the object A with some new properties.

Then I have an method AA that returns the instance of object A, but in my current method BB I use the new instance of object B.

开发者_运维问答Do I have any way to use the return of the method AA to assign in the object B?, How do I assign to B avoiding copy property by property?

class A
{
   string a1 {get; set;}
   // ...
   string a50 {get; set;}
}

class B: A
{
   string bState {get; set;}
   string bMessage {get; set;}
}

class ObjAA
{
   public static AA ReturnAA() 
   {
       AA oAA = new AA();
       //... 
       return oAA;
   }
}

class ObjBB
{
   public void UseBB() 
   {
       BB oBB = new BB();

       var aa = ObjAA.ReturnAA();

       // How do I assign to B avoiding property by property?
   }
}

thanks


Marc Gravell mentions one way, which is fine.

Another is to just have the method return an instance of B for you. How? Use generics.

class ObjAA {
    public static T ReturnA<T>() where T : A, new() {
        T oAA = new T();
        // fill the properties of A
        return oAA;
    }
}

Then:

class ObjBB
{
   public void UseBB() 
   {
       var bb = ObjAA.ReturnA<B>();
       // bb is a B, and the properties it inherits from A are filled
   }
}


Tools like AutoMapper can help this type of switch between similar object types.


Here is a way to copy a base objects properties to an object that extends the base.

I use the following code on those unfortunate occasions when I need to use a base type as a derived type. Yes it is a violation of the Liskov Substitution Principle (LSP) and yes most of the time we favor composition over inheritance. Props to Markus Knappen Johansson whose original answer this is based upon.

This code in the base class:

    public T As<T>()
    {
        var type = typeof(T);
        var instance = Activator.CreateInstance(type);

        if (type.BaseType != null)
        {
            var properties = type.BaseType.GetProperties();
            foreach (var property in properties)
                if (property.CanWrite)
                    property.SetValue(instance, property.GetValue(this, null), null);
        }

        return (T) instance;
    }

Allows:

    derivedObject = baseObect.As<derivedType>()

Since it uses reflection, it is "expensive". Use accordingly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜