나는 모든 GenerateAsync
는 다른 유형의 객체를 생성이비동기 메서드 호출을 사용하여 조건 집합을 사전으로 변환하려면 어떻게해야합니까?
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
의를 다시 작성할 수 있습니다. 뭔가 같은 :
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();
}
}
해결책 :
덕분에 내가 Dictionary<bool, Func<Task>>
을 만드는 아이디어를 떨어 뜨 더 의미가 있기 때문에 IReadOnlyDictionary<RegisterSection, Func<RegisterXml, RegisterGenerationArgs, Task>>
로 대체 @ 피터 duniho의 대답. 두 개의 true/false뿐만 아니라 여러 개의 키. 내가 제대로 코드 예제를 이해한다면
그래서 사전 정말이 작업에 적합한 도구가 아닙니다, 나는
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);
}
거의 다 왔으므로 람다를 '비동기'로 만들어야합니다. – svick
@svick :별로 없습니다. 람다를 async로 만드는 것은 필수적이지만, 사전에 더 근본적인 문제가 있습니다 : 사전을 채울 때'SectionContainedWithin()'메소드를 평가하는 것은'args'가 그 시간에 알려졌다는 것을 가정 할뿐만 아니라, 한 번에 두 개의 항목 만 사전에 포함되며 그 중 하나만 핵심 값인 '참'을 갖습니다. 자세한 내용은 내 게시 된 답변을 참조하십시오. –
@PeterDuniho 네가 맞아, 나는 '사전'문제를 알지 못했다. – svick