扩展方法返回 InvalidCastException

本文关键字:InvalidCastException 返回 方法 扩展 | 更新日期: 2023-09-27 18:36:39

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

我必须在 catch 块中返回 null,所以我有另一个未经处理的异常,也打印了它。

现在,当我尝试运行此代码时,输出是

InvalidCastException NullReferenceException

泛型转换方法抛出无效强制转换异常 尝试了此处找到的解决方案,方法是将(动态)添加到强制转换,结果相同。

请注意,我有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();
    }

}

}

扩展方法返回 InvalidCastException

你应该改变你的静态方法,让它返回一个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);
        }
    }

确保您的"选择"也属于此类型:

IEnumerable<int> selectie = r.TakeRange(10, 1000);
        foreach (int n in selectie)
            Console.Write("{0}; ", n);

没问题,我必须寻求帮助:P

您将try块中Where调用的返回值转换为键入 Reeks

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

但是,任何地方都没有称为 Where 的方法实际返回类型 Reeks 的对象。该代码调用 Enumerable.Where ,它返回某种IEnumerable实现,但绝对不是您自己的类型。

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

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

where 子句返回应转换为列表的枚举器。此外,您可以在 linq 中尝试skiptake以替换上述代码片段。

相关文章:
  • 没有找到相关文章