问题描述
这是一个
我有一个 XDocument
和一个 List< string>
包含我需要掩盖的敏感信息的元素的名称(在本例中用下划线替换)
XDocument xDoc;
列表< string> propertiesToMask;
可以使用传统的 foreach
循环,或者使用带有lamba语法的 .ForEach
方法。
foreach(propertyToMask中的字符串propertyToMask)
{
foreach(xDoc.Descendants(propertyToMask)中的XElement元素)
{
element.SetValue(new string('_',element .Value.Length));
code
$ b propertiesToMask
.ForEach(propertyToMask => xDoc.Descendants(propertyToMask).ToList()
.ForEach(element => element.SetValue (new string('_',element.Value.Length))));
您认为哪种方法最具可读性,为什么?如果你喜欢第二个例子,你将如何展示它以获得最大的可读性?
foreach(propertyToMask中的字符串propertyToMask)
{
foreach(xDoc.Descendants(propertyToMask)中的XElement元素)
{
element.SetValue(new string('_',element。 Value.Length));
$ b 因为间距使得扫描非常简单。第二个是非常混乱,我必须真正阅读它。
This is a question about coding for readability.
I have an XDocument
and a List<string>
of the names of the elements that contain sensitive information that I need to mask (replace with underscores in this example).
XDocument xDoc;
List<string> propertiesToMask;
This can be written in two ways, using traditional foreach
loops, or using .ForEach
methods with lamba syntax.
foreach (string propertyToMask in propertiesToMask)
{
foreach (XElement element in xDoc.Descendants(propertyToMask))
{
element.SetValue(new string('_', element.Value.Length));
}
}
or
propertiesToMask
.ForEach(propertyToMask => xDoc.Descendants(propertyToMask).ToList()
.ForEach(element => element.SetValue(new string('_', element.Value.Length))));
Which approach do you think is the most readable, and why? If you prefer the second example, how would you present it for maximum readability?
解决方案 foreach (string propertyToMask in propertiesToMask)
{
foreach (XElement element in xDoc.Descendants(propertyToMask))
{
element.SetValue(new string('_', element.Value.Length));
}
}
Because the spacing makes it very simple to scan. The second is far to cluttered and I have to actually read it.
这篇关于foreach(... in ...)或.ForEach();就是那个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!