扩展方法 returns InvalidCastException

Extension method returns InvalidCastException

我正在尝试学习如何使用扩展方法并创建了自己的扩展方法。现在我尝试 运行 我的代码,但是 Visual Studio 给了我一个错误,我有一个未处理的 InvalidCastException,所以我处理它并尝试 运行 它。

我不得不在 catch 块中 return null,所以我有另一个未处理的异常,也打印了它。

现在,当我尝试 运行 这段代码时,我的输出是

InvalidCastException NullReferenceException

Generic conversion method throw InvalidCastException 通过向演员添加(动态)来尝试此处找到的解决方案,结果相同。

注意,我有 java 背景,不是 C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{

class Program
{
    static void Main(string[] args)
    {
        Reeks r = new Reeks();
        IEnumerable<int> selectie = r.TakeRange(10, 1000);
        try
        {
            foreach (int i in selectie)
            {
                Console.WriteLine("selectie: {0}", i);
            }
        }
        catch (NullReferenceException)
        {
            Console.WriteLine("NullReferenceException");
        }
        Console.ReadLine();

    }
}

static class MyExtension
{
    public static Reeks TakeRange(this Reeks r, int start, int end)
    {
        try
        {
            return (Reeks)r.Where(i => i > start && i < end);
        }
        catch (InvalidCastException) { 
            Console.WriteLine("InvalidCast"); return null; 
        }
    }
}


public class Reeks : IEnumerable<int>
{

    public Reeks()
    {

    }

    public IEnumerator<int> GetEnumerator()
    {
        int start = 2;
        yield return start;
        for (; ; )
        {
            int nieuw = start * 2;
            yield return nieuw;
            start = nieuw;

        }

    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }


}


}

您应该更改以下行 return (Reeks)r.Where(i => i > start && i < end);return (Reeks)(r.Where(i => i > start && i < end).ToList().AsEnumerable());

where 子句 returns 应转换为列表的枚举器。另外,你可以尝试用linq中的skiptake替换上面的代码片段。

您正在将 try 块中 Where 调用的 return 值转换为键入 Reeks:

return (Reeks)r.Where(i => i > start && i < end);

但是,在任何地方都没有名为 Where 的方法实际上 return 是类型 Reeks 的对象。该代码调用 Enumerable.Where,其中 return 是某种 IEnumerable 实现,但绝对不是您自己的类型。

您必须实现一个名为 Where 的新(扩展或实例)方法,该方法可以在 Reeks 对象上调用,并且 return 是一个 Reeks 对象.或者您可以简单地接受 Where 不是 return 和 Reeks 的事实,而只是期待 IEnumerable<int>

您应该更改您的静态方法,使其 returns 成为 IEnumerable <int>,看看这个:

static class MyReeksExtension {
        public static IEnumerable <int> TakeRange(this IEnumerable<int> r, int start, int end) {
            return r.Where(i => i > start && i < end);
        }
    }

确保你的'selectie'也是这种类型:

IEnumerable<int> selectie = r.TakeRange(10, 1000);

        foreach (int n in selectie)
            Console.Write("{0}; ", n);

没问题,我也得寻求帮助:P