Resharper改变了(当然我的批准):
private static Subdepartment GetSubdepartmentForXMLElement(XElement subdept)
{
return new Subdepartment
{
Id = Convert.ToInt32(subdept.Element("Id")),
AccountId = Convert.ToDouble(subdept.Element("AccountId ")),
Name = subdept.Element("Name")
};
}
......进入这个:
private static Subdepartment GetSubdepartmentForXMLElement(XElement subdept)
{
var xElement = subdept.Element("Id");
if (xElement != null)
{
var element = subdept.Element("AccountId");
if (element != null)
{
var el = subdept.Element("Name");
if (el != null)
{
return new Subdepartment
{
Id = Convert.ToInt32(xElement.Value),
AccountId = Convert.ToDouble(element.Value),
Name = el.Value
};
}
}
}
}
...我必须添加:
return null;
...在倒数第二个大括号之后,允许它编译。</ p>
我喜欢R#,但上面的代码看起来比我的一屁股贵了9倍;这不是一个更好的整合:
private static Subdepartment GetSubdepartmentForXMLElement(XElement subdept)
{
var IdElement = subdept.Element("Id");
var AccountIdElement = subdept.Element("AccountId");
var NameElement = subdept.Element("Name");
if ((IdElement != null) && (AccountIdElement != null) && (NameElement != null))
{
return new Subdepartment
{
Id = Convert.ToInt32(IdElement.Value),
AccountId = Convert.ToDouble(AccountIdElement.Value),
Name = NameElement.Value
};
}
return null;
}
我其实更喜欢这种&#34;风格&#34;由于某种原因:
var IdElement = itemGroup.Element("Id");
var item_group_idElement = itemGroup.Element("item_group_id");
var nameElement = itemGroup.Element("name");
if ((null == IdElement) || (null == item_group_idElement) || (null == nameElement)) return null;
return new ItemGroup
{
Id = Convert.ToInt32(itemGroup.Element("Id").Value),
item_group_id = itemGroup.Element("item_group_id").Value,
name = itemGroup.Element("name").Value
};
答案 0 :(得分:4)
此:
private static Subdepartment GetSubdepartmentForXMLElement(XElement subdept)
{
return new Subdepartment
{
Id = Convert.ToInt32(xElement.Value),
AccountId = Convert.ToDouble(element.Value),
Name = el.Value
};
}
......甚至没有编译。 <{1}},xElement
和element
未声明。
但是,resharper不应该抱怨这个:
el
Resharper代码更正一次只适用于一个问题,这就是为什么你最终得到OP中的嵌套混乱。如果您从一开始就仔细编写代码,则需要执行这些单一问题修复。
就个人而言,我更喜欢减少嵌套,并希望这样做更好一点:
private static Subdepartment GetSubdepartmentForXmlElement(XElement subdept)
{
if (subdept == null) throw new ArgumentNullException("subdept");
var idElement = subdept.Element("Id");
var accountIdElement = subdept.Element("AccountId");
var nameElement = subdept.Element("Name");
if (idElement != null && accountIdElement != null && nameElement != null)
{
return new Subdepartment
{
Id = Convert.ToInt32(idElement.Value),
AccountId = Convert.ToDouble(accountIdElement.Value),
Name = nameElement.Value
};
}
return null;
}
ReSharper也不会抱怨这个。