我有一个大的,抽象的,类InfoBase
,有很多属性。然后有一些子类,它们有一些属性。我将收到一个带有信息的对象来实现InfoBase
的子类对象,然后将返回该对象,如下所示:
private static InfoBase CreateInfo(Dictionary<string, string> userInput) {
InfoBase info;
if(userInput["InfoType"] == "SomeInfo") {
info = new SomeInfo {
sharedData1 = Process(userInput["data1"]),
sharedData2 = ProcessDifferently(userInput["data2"] + userInput["AuxData"]),
// ...
specialData1 = Something(userInput["blah"])
};
}
else if(userInput["InfoType"] == "OtherInfo") {
// ... And so on
}
return info;
}
info
对象的几乎所有字段都将以相同的方式初始化,因此我想分享初始化而不是复制/粘贴它,只需更改细节。我想用初始化列表进行共享初始化,而不是有20行info.data1 = ...;
。这可能吗?理想情况下,这样的事情:
InfoBase info = WhateverMagicStuff {
sharedData1 = // ...
};
SomeInfo specificInfo = SomeInfo(info);
specificInfo.specialData1 = // ...
答案 0 :(得分:0)
public void PopulateInfoBase(InfoBase infoToPopulate, WhateverUserInputIs userInput)
{
infoToPopulate.sharedData1 = Process(userInput["data1"]);
infoToPopulate.sharedData2 = ProcessDifferently(userInput["data2"] + userInput["AuxData"]);
etc etc
}
在实例化所需的特定子类(并填充其“特殊”数据)后调用上述函数。
答案 1 :(得分:0)
在if else块之后分配共享数据。
private static InfoBase CreateInfo(Dictionary<string, string> userInput) {
InfoBase info;
if(userInput["InfoType"] == "SomeInfo") {
info = new SomeInfo {
// ...
specialData1 = Something(userInput["blah"])
};
}
else if(userInput["InfoType"] == "OtherInfo") {
// ... And so on
}
else { ... }
info.sharedData1 = Process(userInput["data1"]),
info.sharedData2 = ProcessDifferently(userInput["data2"] + userInput["AuxData"]),
return info;
}