我有以下功能,工作和循环通过3个可能的水平。 有没有办法做到以下功能相同,但不必做多个foreach语句? 基本上反应变量列表可以包含多个GroupResponseTypes 每一种可以包含多个ElementResponseBaseTypes 可以是多种类型本身 我很感兴趣,在ElementResponseType 而每ElementResponseBaseType本身找到一个值可以是GroupResponseType,它包含多种类型。C#如何避免多个foreach和if语句
所以我在看一个简单的方式,通过整个结构进行扫描特定Element.Reference 和返回相关的值
任何帮助深表感谢
public static string GetValueFromFormField(List<ResponseBaseType> responses, string fieldref)
{
string fieldvalue = String.Empty;
foreach (GroupResponseType groups in responses)
{
foreach (ElementResponseBaseType firstelements in groups.Responses)
{
if (firstelements.GetType() == typeof(ElementResponseType))
{
if (firstelements.Element.Reference == fieldref)
{
ElementResponseType firstelement = new ElementResponseType();
firstelement = (ElementResponseType)firstelements;
fieldvalue = firstelement.Value;
}
}
else if (firstelements.GetType() == typeof(GroupResponseType))
{
GroupResponseType secondgroup = new GroupResponseType();
secondgroup = (GroupResponseType)firstelements;
foreach (ElementResponseBaseType secondelements in secondgroup.Responses)
{
if (secondelements.GetType() == typeof(ElementResponseType))
{
if (secondelements.Element.Reference == fieldref)
{
ElementResponseType secondelement = new ElementResponseType();
secondelement = (ElementResponseType)secondelements;
fieldvalue = secondelement.Value;
}
}
else if (secondelements.GetType() == typeof(GroupResponseType))
{
GroupResponseType thirdgroup = new GroupResponseType();
thirdgroup = (GroupResponseType)secondelements;
foreach (ElementResponseBaseType thirdelements in thirdgroup.Responses)
{
if (thirdelements.GetType() == typeof(ElementResponseType))
{
if (thirdelements.Element.Reference == fieldref)
{
ElementResponseType thirdelement = new ElementResponseType();
thirdelement = (ElementResponseType)thirdelements;
fieldvalue = thirdelement.Value;
}
}
}
}
}
}
}
}
return fieldvalue;
}
你有没有尝试使用LINQ实现更清晰的外观过滤代码? – 2014-08-28 14:25:29
你不应该测试每个对象的类型并采取不同的行为,你应该使用多态。每种类型都应根据其个体差异实现一种通用方法,从而允许使用这些类型的代码进行编写,而无需知道特定对象的公共接口的哪些派生类型。 – Servy 2014-08-28 14:29:32
嗨,是的,我尝试使用链接在第一个地方,但无法工作/使其迭代通过可能是n不同层次的GroupResponseType – paulmezza 2014-08-28 14:32:18