Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

c# - What's the benefit of .Cast over .Select?

I have a type with implicit conversion operators to most base types and tried to use .Cast<string>() on a collection of this type, which failed. As I dug into it, I noticed that casting via as doesn't use implicit or explicit conversion and just won't compile, so I guess that's where .Cast falls down. So this fails

var enumerable = source.Cast<string>();

but this works

var enumerable = source.Select(x => (string)x);

So what's the benefit of Cast? Sure, it's a couple of characters shorter, but seems a lot more limited. If it can be used for conversion, is there some benefit other than the more compact syntax?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Cast usage

The benefit of Cast comes when your collection only implements IEnumerable (ie. not the generic version). In this case, Cast converts all elements to TResult by casting, and returns IEnumerable<TResult>. This is handy, because all the other LINQ extension methods (including Select) is only declared for IEnumerable<T>. In code, it looks like this:

IEnumerable source = // getting IEnumerable from somewhere

// Compile error, because Select is not defined for IEnumerable.
var results = source.Select(x => ((string)x).ToLower());

// This works, because Cast returns IEnumerable<string>
var results = source.Cast<string>().Select(x => x.ToLower());

Cast and OfType are the only two LINQ extension methods that are defined for IEnumerable. OfType works like Cast, but skips elements that are not of type TResult instead of throwing an exception.

Cast and implicit conversions

The reason why your implicit conversion operator is not working when you use Cast is simple: Cast casts object to TResult - and your conversion is not defined for object, only for your specific type. The implementation for Cast is something like this:

foreach (object obj in source)
    yield return (TResult) obj;

This "failure" of cast to do the conversion corresponds to the basic conversion rules - as seen by this example:

YourType x = new YourType(); // assume YourType defines an implicit conversion to string
object   o = x;

string bar = (string)x;      // Works, the implicit operator is hit.
string foo = (string)o;      // Fails, no implicit conversion between object and string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...