我有多个验证布尔属性,可能需要或不需要。如果需要它们,则需要对其进行检查以进行验证。因此,我必须构建多个 if 语句来处理每个属性。我的问题是是否有更好的方法来维护这一点,而不必为每个新属性编写 if 。
public class ProductionNavbarViewModel
{
public bool IsProductionActive { get; set; }
public bool ValidatedComponents { get; set; }
public bool ValidatedGeometries { get; set; }
public bool ValidatedPokayokes { get; set; }
public bool ValidatedTechnicalFile { get; set; }
public bool ValidatedStandardOperationSheet { get; set; }
public bool ValidatedOperationMethod { get; set; }
public bool IsComponentsRequired { get; set; }
public bool IsGeometriesRequired { get; set; }
public bool IsPokayokesRequired { get; set; }
public bool IsTechnicalFileRequired { get; set; }
public bool IsStandardOperationSheetRequired { get; set; }
public bool IsOperationMethodRequired { get; set; }
public bool IsProductionReadyToStart()
{
if (IsComponentsRequired)
{
return ValidatedComponents;
}
if (IsComponentsRequired && IsGeometriesRequired)
{
return ValidatedComponents && ValidatedGeometries;
}
if (IsComponentsRequired && IsGeometriesRequired && IsPokayokesRequired)
{
return ValidatedComponents && ValidatedGeometries && ValidatedPokayokes;
}
if (IsComponentsRequired && IsGeometriesRequired && IsPokayokesRequired && IsTechnicalFileRequired)
{
return ValidatedComponents && ValidatedGeometries && ValidatedPokayokes && ValidatedTechnicalFile;
}
if (IsComponentsRequired && IsGeometriesRequired && IsPokayokesRequired && IsTechnicalFileRequired && ValidatedStandardOperationSheet)
{
return ValidatedComponents && ValidatedGeometries && ValidatedPokayokes && ValidatedTechnicalFile && ValidatedStandardOperationSheet;
}
if (IsComponentsRequired && IsGeometriesRequired && IsPokayokesRequired && IsTechnicalFileRequired && IsStandardOperationSheetRequired && IsOperationMethodRequired)
{
return ValidatedComponents && ValidatedGeometries && ValidatedPokayokes && ValidatedTechnicalFile && ValidatedStandardOperationSheet && ValidatedOperationMethod;
}
return false;
}
}
编辑
编写此代码时出现问题。目的是验证所有选项,它们必须是必要的,如果只有一个属性满足条件,则无法返回。
谢谢大家,我会在评论中尝试一些建议的方法,然后我会发布结果
更新
我现在提供了一个简短的版本,并且根据每个人的评论更具可读性,直到我可以尝试每种方法。编辑以根据@Alexander Powolozki 的回答组合所有表达式。
public bool IsProductionReadyToStart()
{
bool isValid = true;
isValid &= !IsComponentsRequired || ValidatedComponents;
isValid &= !IsGeometriesRequired || ValidatedGeometries;
isValid &= !IsPokayokesRequired || ValidatedComponents;
isValid &= !IsTechnicalFileRequired || ValidatedTechnicalFile;
isValid &= !IsStandardOperationSheetRequired || ValidatedStandardOperationSheet;
isValid &= !IsOperationMethodRequired || ValidatedOperationMethod;
return isValid;
}