对于这样的代码,“物化”是一个好名字,还是有更好的(和官方的)名字?
enumerable as ICollection<T> ?? enumerable .ToArray()
编辑:我澄清了代码(及其目的)
// or "MaterializeIfNecessary"
public static IEnumerable<T> Materialize<T>(this IEnumerable<T> source)
{
// if you use code analysis tools like resharper, you may have to return a
// different type to turn off warnings - even a placeholder interface like
// IMaterializedEnumerable<T> : IEnumerable<T> { }
if (source == null) return null;
return source as ICollection<T> ?? source.ToArray();
}
问题:
static void Save(IEnumerable<string> strings)
{
// The following code is Resharper suggested solution to
// "Possible multiple enumeration of IEnumerable" warning
// ( http://confluence.jetbrains.com/display/ReSharper/Possible+multiple+enumeration+of+IEnumerable ):
strings = strings as string[] ?? strings.ToArray(); // you're not calling
// ToArray because you
// need an array, here
if (strings.Any(s => s.Length >= 255)) throw new ArgumentException();
File.AppendAllLines("my.path.txt", strings);
}
使用扩展方法,第一行应该更具声明性:
strings = strings.MaterializeIfNecessary();