What's the benefit of .Cast over .Select?

后端 未结 2 1918
粉色の甜心
粉色の甜心 2020-12-09 01:28

I have a type with implicit conversion operators to most base types and tried to use .Cast() on a collection of this type, which failed. As I dug

2条回答
  •  無奈伤痛
    2020-12-09 01:52

    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. This is handy, because all the other LINQ extension methods (including Select) is only declared for IEnumerable. 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
    var results = source.Cast().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
    

提交回复
热议问题