将类赋值给构造函数中对象的副本

本文关键字:对象 副本 构造函数 赋值 | 更新日期: 2023-09-27 18:07:18

如何使用返回正确对象类型的方法将其分配为class对象。我认为我可以写代码来更好地解释我的问题。

public class Foo
{
    public int FooNumer = 0;
    public Foo()
    { 
        this = FooGenerator.GetNewFoo(); //Does not work, is read only
    }
}
public static class FooGenerator()
{
  public static Foo GetNewFoo()
  {
    return new Foo(){FooNumer = 1};
  }
}

我希望我实例化的新Foo类,是来自FooGenerator的对象的副本。

是只读的,因此上面的代码不能工作。有没有简单的解决办法,有没有可能,我是不是忽略了什么愚蠢的东西?

编辑:

添加额外的伪代码来更好地解释我的目的。

public class FooBase
{
    public string FooNumer = 0;
    public string Type;
    public string Count;
    public string Creator;
    public FooBase()
    {
    }
    public FooBase(DataSet ds)
    {
        FooNumer = ds.Rows[0]["Number"];
        Type =  ds.Rows[0]["Type"];
        Count =  ds.Rows[0]["Count"];
        Creator =  ds.Rows[0]["Creator"];
    }
    public FooBase(int id)
    { 
        this = FooDAL.GetFooFromDatabase(id);
    }
}
public class FooDAL
{
    public static GetFooFromDatabase(int fooID)
    {
        DataSet data = GetDataSetFromDatabase(fooID);
        return new FooBase(data);
    }
}
public class FooBaby : FooBase
{
    public string BabyWeight;
     FooBaby(int id) :
         base(id)
    {
        //Now by using this constructor, all the properties of FooBaby base(FooBase) will be instantiated in the base constructor
    }
}

将类赋值给构造函数中对象的副本

您可以使用copy constructor

public class Foo
{
    public int FooNumer = 0;
    public Foo() { }
    public Foo(Foo copyFrom)
    {
        this.FooNumer = copyFrom.FooNumer;
    }
}
var foo = new Foo(FooGenerator().GetNewFoo());

FooGenerator实际上是根据你在

中发送的数字从数据库中提取一个项目

这听起来像一个Flyweight Factory。你可以这样实现:

public class Foo
{
    public int FooNumber {get;}
    internal Foo(int fooNumber)  // internal so only clients within the same assembly can use it
    { 
        FooNumber = fooNumber;
    }
}
public static class FooGenerator()
{
  public static Dictionary<int, Foo> instances = new Dictionary<int, Foo>();
  public static Foo GetFoo(int fooNumber)
  {
    if(!instances.ContainsKey(fooNumber))
       // this Foo has not yet been created, so create and add it
       instances.Add(fooNumber,new Foo(fooNumber));
  }
  // pull the Foo from the list by fooNumber
  return instances[fooNumber];
}