Is there a way to make the .NET Cast<T> extension method use user defined implicit cast operators? [duplicate]

StackOverflow https://stackoverflow.com/questions/23436918

سؤال

When I define an implicit cast operator, then attempt to invoke it on a whole collection of objects at once using the Cast<T> extension method, I get an InvalidCastException. Is there any workaround for this problem?

هل كانت مفيدة؟

المحلول

No, Cast treats each item as Object and casts it to the target type, so it can't use user-defined conversions because conversion are resolved statically. Instead you can just do this:

collection.Select(x => (YourType)x)

نصائح أخرى

No.

Cast is a CLR method. It does not incorporate C# specific binding rules because it is independent of any specific CLR language. Implicit conversions are specific to a few .NET languages.

You have to create your own version of Cast.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top