我已经编程了 15 年,但我对 C# 很陌生,并且总体上对强类型语言缺乏经验,所以如果这是一个 super 菜鸟问题,我深表歉意。
我试图避免大量重复代码,但无法找到一种方法来完成我想要的事情。这是我目前拥有的示例:
class BaseModel {
string sharedProperty1;
string sharedProperty2;
string sharedProperty3;
string sharedProperty4;
string sharedProperty5;
string sharedProperty6;
}
class ExtendedModelA : BaseModel {
string exclusivePropertyA;
}
class ExtendedModelB : BaseModel {
string exclusivePropertyB;
}
// --------
dynamic finalModel;
if( conditionA )
{
finalModel = new ExtendedModelA{
sharedProperty1 = 1,
sharedProperty2 = 2,
sharedProperty3 = 3,
sharedProperty4 = 4,
sharedProperty5 = 5,
sharedProperty6 = 6,
exclusivePropertyA = "foo"
};
}
else
{
finalModel = new ExtendedModelB{
sharedProperty1 = 1,
sharedProperty2 = 2,
sharedProperty3 = 3,
sharedProperty4 = 4,
sharedProperty5 = 5,
sharedProperty6 = 6,
exclusivePropertyB = "bar"
};
}
正如您所看到的,存在大量冗余,因为初始化值的唯一区别是每个属性上的最后一个 exclusiveProperty
(在我的具体情况下,我有大约 30 个属性在每一半中重复) if/else
并且只有 2 或 3 个唯一)。我想做的是使用所有 sharedProperty
值初始化"template"模型一次,并且在 if/else
内只需要初始化 ExclusiveProperty
值。
这里有一些伪代码来说明我想做的事情的概念,但我还无法使其工作。
var template = new BaseModel
{
sharedProperty1 = 1,
sharedProperty2 = 2,
sharedProperty3 = 3,
sharedProperty4 = 4,
sharedProperty5 = 5,
sharedProperty6 = 6
};
dynamic finalModel;
if( conditionA )
{
finalModel = new ExtendedModelA{template};
finalModel.exclusivePropertyA = "foo";
}
else
{
finalModel = new ExtendedModelB{template};
finalModel.exclusivePropertyB = "foo";
}
我熟悉可用于接受"template"和“扩展”作为参数的工厂模式,但这与简单地保留重复项一样多的代码,所以我正在寻找一个更...直接?方法来做到这一点。
最佳答案
我认为在不重复代码的情况下执行此操作的最简单方法是在 if else block 中使用唯一属性创建对象,然后最后分配所有共享属性。这将防止您必须重复代码。
BaseModel finalModel = null;
if (conditionA)
{
finalModel = new ExtendedModelA()
{
exclusivePropertyA = "some value";
};
}
else
{
finalModel = new ExtendedModelB()
{
exclusivePropertyB = "some other value";
};
}
finalModel.sharedProperty1 = "asdf";
// assign the rest of the values
您还可以有一个基本模型的构造函数,它将基本模型作为参数并将所有值分配给新对象。这基本上是使用原始版本作为模板来创建新版本。然后,您可以使用模板创建扩展类并将其传递给基本构造函数。
class BaseModel
{
public string sharedProperty1 { get; set; }
public string sharedProperty2 { get; set; }
public string sharedProperty3 { get; set; }
public string sharedProperty4 { get; set; }
public string sharedProperty5 { get; set; }
public string sharedProperty6 { get; set; }
public BaseModel(BaseModel t)
{
//assign template properties
}
public BaseModel()
{
}
}
class ExtendedModelA : BaseModel
{
public string exclusivePropertyA { get; set; }
public ExtendedModelA(BaseModel t)
: base(t)
{
}
}
class ExtendedModelB : BaseModel
{
public string exclusivePropertyB { get; set; }
public ExtendedModelB(BaseModel t)
: base(t)
{
}
}
然后使用它就是
BaseModel template = new BaseModel()
{
//assign values
};
ExtendedModelA = new ExtendedModelA(template)
{
exlusivePropertyA = "asdf";
};
关于c# - 如何从另一个对象初始化一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34097986/