"Материализовать" хорошее имя для такого кода, или есть лучшее (и официальное) имя?
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();
AsReadOnly
илиToReadOnlyCollection
- person Magnus   schedule 12.02.2013AsReadOnlyCollection
лучше описывает результат - person Sergey Berezovskiy   schedule 12.02.2013IList<string>
. - person Magnus   schedule 12.02.2013IEnumerable<T>
как твердый тип коллекции, поскольку он также может быть просто запросом. И у вас это неплохо получилось (я имею в виду реализацию метода). Но здесь есть одна загвоздка: ваш метод возвращает либо существующую коллекцию (простым приведением), либо новую коллекцию. Для первой операции такой глагол, какMaterialize
, хорош в качестве имени функции, поскольку вы действуете в списке, но для второй операции что-то вродеTo...
более согласовано с функциями, определенными фреймворком. - person nawfal   schedule 28.09.2013AsCollection
или даже простоMaterialize
неплохо. Еще одно предложение - вернутьICollection<T>
, поскольку вы выполняете вызов, и в большинстве случаев здесь имеет смысл что-то более конкретное, чемIEnumerable<T>
. См. Соответствующую ссылку здесь: stackoverflow.com/questions/4621561/ - person nawfal   schedule 28.09.2013