IEnumerable.Cast won't work even if an explicit cast operator is defined?

后端 未结 5 1731
天涯浪人
天涯浪人 2020-12-03 17:20

I have an explicit conversion defined from type Bar to type Foo.

public class Bar
{
  public static explicit operator Foo(Bar bar)
         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 18:12

    As all other answers pointed type is not known in compile time since Cast method is not generic. It holds type of object and makes a explicit cast to T. this fails because you don't have conversion operator from object to Foo. And that is not possible also.

    Here is a work around using dynamics in which cast will be done in runtime.

    public static class DynamicEnumerable
    {
        public static IEnumerable DynamicCast(this IEnumerable source)
        {
            foreach (dynamic current in source)
            {
                yield return (T)(current);
            }
        }
    }
    

    Then use it like

     var result = bars.DynamicCast();//this works
    

提交回复
热议问题