简体   繁体   中英

Implicit cast using Linq

Say I have a list with integers ( var identifiers = Enumerable.Empty<int>() ).

With this list I can cast the individual items to another type:

var castedIdentifiersLong = identifiers.Cast<long>();
var castedIdentifiersString = identifiers.Cast<string>();

We can use Select<TSource, TTarget>() to use implicit casting:

var mappedIdentifiersLong = identifiers.Select<int, long>(x => x);
var mappedIdentifiersString = identifiers.Select<int, string>(x => x);

Obviously the last statement fails, because int cannot be implicitly casted to string . This is intentionally.

Is there a way that I can define an extension method (say CastImplicitly<T> ), where I can only define one of the two generic types and it would figure out the first type from the source enumerable?

var unwanted = identifiers.ImplicitCast<string>();
var wanted = identifiers.ImplicitCast<long>();

In this case unwanted shouldn't even compile, because int isn't implicitly castable to string . But on the other hand, wanted should compile, because it is implicitly castable to long .

Is there a way that I can define an extension method (say CastImplicitly<T> ), where I can only define one of the two generic types and it would figure out the first type from the source enumerable?

Not if the input is generic. The compiler cannot partially infer generic parameters - you either have to specify all generic parameters or none and let the compiler infer.

Even if you could , the compiler still would not allow an implicit cast between generic types.

If you want the compiler to identify invalid casts at compile-time you could do an explicit cast:

var mappedIdentifiersString = identifiers.Select(x => (string)x);  // fails at compile time if x is an int.

It may not catch every possible invalid cast at compile-time (eg casts to/from object are always allowed at compile-time) but it does fail for your specific int to string scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM