Explicit/implicit cast operator fails when using LINQ's .Cast() operator

前端 未结 1 658
悲哀的现实
悲哀的现实 2020-12-03 09:54

I am trying to use a class that has a explicit (but also fails with implicit) cast operator that fails when using LINQ\'s Cast() function. Here is the

相关标签:
1条回答
  • 2020-12-03 10:34

    When you define explicit/implicit cast operators, they are bound at call-sites at compile-time. That's why the first line works: the compiler can work out all the type information needed, and so it can substitute your custom explicit cast operator for the default one.

    However, since the Cast<T> just performs a generic cast, the compiler doesn't know about your operator, and thus it is ignored. Result: invalid cast exception.

    You can get around this by instead performing a .Select(x => (DatabaseInfo)x). Alternatively, you could add on a method called ToDatabaseInfo(), so that you're not hiding what's actually going on.

    0 讨论(0)
提交回复
热议问题