在构造函数中将类分配给副本对象

时间:2015-08-11 18:43:21

标签: c# visual-studio-2013 constructor instantiation

如何使用返回正确对象类型的方法将其指定为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 Cass是来自FooGenerator的对象的副本。

这是readonly,因此上面的代码不起作用。有一个简单的解决方案,这是可能的,我是否忽略了一些愚蠢的东西?

编辑:

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

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
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用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());

答案 1 :(得分:0)

  

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];
}