10

In my project I have a MyClass which implements IMyClass. I need to return a list of IMyClass by transforming a list of other items. For simplicity's sake, assume that I can create a MyClass just by passing another item into its constructor, i.e. new MyClass(item).

Consider the following two lines, which (as far as I know) produce the same result:

var option1 = items.Select(item => new MyClass(item)).Cast<IMyClass>().ToList()
var option2 = items.Select(item => new MyClass(item) as IMyClass).ToList()

It seems to me that option #1 would require a double enumeration, once to cast all the items to my interface and once to generate the list. If I'm right then option #2 would be smarter. However, I've never seen any code using something like option #2, and I tend to assume that I'm not smart enough to come up with something clever that the rest of the C# community did not.

On a side note, I think option #2 is more aesthetically pleasing, but that's just me.

My question is: is my option #2 a better idea like I think it is? Are there are any gotchas I'm missing or other reasons why I'd want to stick with option #1? Or am I perhaps comparing two stupid ideas when there is a smarter third one that I'm missing completely?

4

4 に答える 4

18

私はオプション3に行きます:

var option3 = items.Select<Foo, IMyClass>(item => new MyClass(item))
                   .ToList()

または、使用せずにas通常どおりキャストします。

var option4 = items.Select(item => (IMyClass) new MyClass(item))
                   .ToList()

これらは両方とも、 を使用するよりもきれいに見えCastます。

ToListああ、C# 4 と .NET 4 の時点では (共分散のため)、代わりに型引数を呼び出しに入れることができます。

var option5 = items.Select(item => new MyClass(item))
                   .ToList<IMyClass>()
于 2013-03-01T17:23:34.993 に答える
1

Select にはいつでも明示的な型引数を指定できます

   var option2 = items.Select<IItem,IMyClass>(item => new MyClass(item)).ToList();

ここで、IItem は項目をキャストできる型またはインターフェイスです。

于 2013-03-01T17:28:39.297 に答える