【发布时间】: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