私はすべてのGenerateAsync
は異なる型のオブジェクトを生成し、この非同期メソッド呼び出しを使用してif条件のセットをDictionaryに変換するにはどうすればよいですか?
if (SectionContainedWithin(args, RegisterSection.StudentPersonalData))
schoolRegister.StudentPersonalData = await _sectionGeneratorsProvider.StudentPersonalDataGenerator.GenerateAsync(args);
if (SectionContainedWithin(args, RegisterSection.StudentAttendances))
schoolRegister.StudentAttendances = await _sectionGeneratorsProvider.StudentMonthAttendancesGenerator.GenerateAsync(args);
if (SectionContainedWithin(args, RegisterSection.Grades))
schoolRegister.Grades = await _sectionGeneratorsProvider.GradesGenerator.GenerateAsync(args);
// More generating here ...
のように見えるいくつかのメソッド呼び出しを持っています。
public interface IGenerator<TResult, in TArgs>
{
Task<TResult> GenerateAsync(TArgs args);
}
にはどうすればいいので、私はアクションと条件のリストを定義することができますし、それらを反復処理、それらのif
Sを書き換えることができます。 のような何か:
var sections = new Dictionary<bool, Func<Task>>()
{
{
SectionContainedWithin(args, RegisterSection.StudentPersonalData),
() => schoolRegister.StudentPersonalData = await _sectionGeneratorsProvider.StudentPersonalDataGenerator.GenerateAsync(args);
},
// More generating here ...
}
foreach(var item in sections)
{
if(item.Key)
{
await item.Value();
}
}
SOLUTION:
おかげで、私はDictionary<bool, Func<Task>>
を作成するためのアイデアを落とし、それがより理にかなっているのでIReadOnlyDictionary<RegisterSection, Func<RegisterXml, RegisterGenerationArgs, Task>>
でそれを置き換える@ピーター・dunihoの答えに。 複数のキーで、2つの真偽のみではありません。
は、だから私は私が正しくコード例を理解していれば、辞書は本当にこの仕事のための適切なツールではありません
private IReadOnlyDictionary<RegisterSection, Func<RegisterXml, RegisterGenerationArgs, Task>> CreateSectionActionsDictionary()
{
return new Dictionary<RegisterSection, Func<RegisterXml, RegisterGenerationArgs, Task>>
{
{ RegisterSection.RegisterCover, async(reg, args) => reg.Cover = await _sectionGenerators.RegisterCoverGenerator.GenerateAsync(args) },
{ RegisterSection.StudentPersonalData, async(reg, args) => reg.StudentPersonalData = await _sectionGenerators.StudentPersonalDataGenerator.GenerateAsync(args)},
// Add more generating here ...
};
}
private async Task GenerateSectionsAsync(RegisterGenerationArgs args, RegisterXml reg)
{
foreach (var sectionAction in SectionActions)
if (SectionContainedWithin(args, sectionAction.Key))
await sectionAction.Value(reg, args);
}
ほとんどの場合、lambdaを非同期にする必要があります。 – svick
@svick:そうではありません。ラムダを非同期にすることは必須ですが、辞書にはより根本的な問題があります:辞書を作成する際に 'SectionContainedWithin()'メソッドを評価すると、 'args'がその時に認識されているだけでなく、一度に2つの項目だけが辞書に登録され、そのうちの1つだけがキー値「真」を持つことになります。詳細については、私の投稿された回答を参照してください。 –
@PeterDunihoあなたが正しいです、私は 'Dictionary'の問題を認識しませんでした。 – svick