1

「マテリアライズ」はこのようなコードの良い名前ですか、それとももっと良い (そして公式の) ものはありますか?

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();
4

2 に答える 2

1

As @Magnus already suggested, ToReadOnlyCollection is a good descriptive name for your method. Also I think AsReadOnlyCollection is not that good name. Usually AsXXX methods do not covert or wrap source. Such methods simply return source as one of interfaces already implemented by source. You can use such method instead of casting.

And Materialize tells totally nothing about intent of method. What does it mean? I will be able to touch my sequence with hands? It will be printed on paper? Saved to file?

And yes, I also don't understand why you need to convert IEnumerable which is already read only to ReadOnlyCollection.

于 2013-02-11T20:29:01.527 に答える
1

私はそれを呼びますToReadOnlyCollection。関数が実際に行っていることに関する詳細情報を提供します。
ソースの具体化に関しては、 が呼び出された場合にのみそうするようですToArray()。(ソースだけをラップしても実現しません)

于 2013-02-11T20:23:13.800 に答える