【问题标题】:Assigning Class To Copy Of object in constructor在构造函数中将类分配给对象的副本
【发布时间】:2015-08-11 18:43:21
【问题描述】:

如何使用返回正确对象类型的方法将其分配为 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 的对象的副本。

这是只读的,因此上面的代码将不起作用。有没有一个简单的解决方案,这可能吗,我忽略了一些愚蠢的事情吗?

编辑:

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

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

【问题讨论】:

  • 看起来你想实现单例模式...
  • @RonBeyer 我不认为我会......? FooGenerator 确实根据您发送的数字从数据库中提取一个项目,我只是在这里进行了简化。
  • 您不能将this 重新分配给构造函数(或其他任何地方)。听起来您已经有了工厂方法,因此将Foo 构造函数设为内部应该会强制客户端使用工厂方法。如果您有理由不想这样做,请编辑您的问题。
  • @DStanley 我知道我不能分配给这个。原因是现在我有一个继承自 Foo 的 FooBaby,需要使用 Foo 的构造函数来创建。
  • 您希望父类创建派生类?这似乎倒退了。或许你也应该为FooBaby 添加伪代码?

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


【解决方案1】:

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

【讨论】:

  • 是的,这行得通,但它是一个有很多属性的类,所以这是最后的手段
【解决方案2】:

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

【讨论】:

    最近更新 更多