如何通过派生类设置基类的所有属性

时间:2019-04-24 12:15:39

标签: c# .net

public BaseClass
{
    prop abc;
    prop pqr;
    prop xyz;    
}

public DerivedClass : BaseClass
{
   prop New1;
   prop New2;

  //constructor
  public DerivedClass(BaseClass baseObj,someMore params)
  {
      this.abc = baseObj.abc;
      this.pqr = baseObj.pqr;
      this.xyz = baseObj.xyz;
      /* I do not want to do this for each and every property as I have more than 40 properties */

  }
}

上面的代码中如何设置派生类的所有属性,这些属性在派生类中与基类相同。

在我的派生类中 我可以在不使用 Automapper Reflection

的情况下完成以下类型的事情来实现上述目标吗?
public DerivedClass(BaseClass baseObj,someMore params):base(baseObj) //or something similar
{
}

2 个答案:

答案 0 :(得分:1)

首先,您应该在基类中初始化属性,而不是在派生类中初始化属性(因为参数和基类都共享同一类型的类)。

要复制属性,除了AutoMapper(我发现它真的很慢)和反射(这很难实现和维护)之外,一种简单,非常有效的方法是使用开源库Omu.ValueInjecter:

NuGet安装库:

Install-Package ValueInjecter -Version 3.1.3

然后,按如下所示在构造函数中使用它:

using Omu.ValueInjecter;

public abstract class BaseClass
{
    protected BaseClass(BaseClass baseObj)
    {
        this.InjectFrom(baseObj);
    }

    public string Abc { get; set; }
    public int Pqr { get; set; }
    public object Xyz { get; set; }
}

public class DerivedClass : BaseClass
{
    public DerivedClass(BaseClass baseObj, int new1, object new2) : base(baseObj)
    {
        New1 = new1;
        New2 = new2;
    }

    public int New1 { get; set; }
    public object New2 { get; set; }
}

第一次运行此代码时,它将创建一个映射器并将其存储在内存中,因此接下来的几次执行相同的操作会更快。

如果您不想使用值注入器或任何其他库,只需在基类中手动设置属性即可。

public abstract class BaseClass
{
    protected BaseClass(BaseClass baseObj)
    {
        Abc = baseObj.Abc;
        Pqr = baseObj.Pqr;
        Xyz = baseObj.Xyz;
    }

    [...]
}

答案 1 :(得分:1)

您可以使用原型模式。如果使用C#,请参考以下代码:

public abstract class BaseClass
{
    public int a;
    public int b;
    public int c;

    public abstract BaseClass Clone();
}

public class DerivedClass : BaseClass
{
    public int new1;
    public int new2;

    public override BaseClass Clone()
    {
        return this.MemberwiseClone() as BaseClass;
    }

    public override string ToString()
    {
        return string.Format("{0}{1}{2}{3}{4}", a, b, c, new1, new2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        DerivedClass AClass = new DerivedClass();
        AClass.a = 1;
        AClass.b = 2;
        AClass.c = 3;

        DerivedClass BClass = AClass.Clone() as DerivedClass;
        BClass.new1 = 4;
        BClass.new2 = 5;

        Console.WriteLine(BClass.ToString());
    }
}

它来自https://mobilechos.blogspot.com/2019/04/prototype-pattern-with-csharp.html