首页 > 解决方案 > 为什么在使用 IEnumerator 类列表时无法在扩展方法中访问类方法

问题描述

这是我的通用类

public class CustomClass<T>
    {
        public T Data { set; get; }
        public T getData()
        {
            return Data;
        }
    }

这是我的主要方法

static void Main(string[] args)
        {
            mylist = new List<CustomClass<int>>();
            CustomClass<int> customClass = new CustomClass<int>();
            customClass.Data = 10;
            CustomClass<int> customClass1 = new CustomClass<int>();
            customClass1.Data = 10;
            mylist.Add(customClass);
            mylist.Add(customClass1);
            CustomClass<int> custom = new CustomClass<int>();
            custom.Data = 20;
            mylist.Add(custom);
            Console.WriteLine(mylist[0].getData());
            Console.WriteLine("----------All----------");
            Console.WriteLine(value: mylist.CustomAll('%', 3, AllAny));
            }

这是我想接收自定义类数据但显示错误的扩展

public static class CustomOperation
    {

        public static bool CustomAll<T>(this IEnumerable<T> e, char symbol, int compare, Action<List<T>, int, char, bool> func)
        {
            e[0].Data// Error here I want CustomClass Data
            return true;
        }

标签: c#genericsextension-methodsienumerable

解决方案


请注意,您的扩展方法也适用于List<string>,以及List<string>(实际上是任何类型的List):

// This compiles!
var intList = new List<int> {1,2,3};
intList.CustomAll('a', 0, (a,b,c,d) => {});

e[0]那么将是一个int,那么会e[0].Data是什么?int没有会员叫Data

这不是唯一的问题,它也可以在任何IEnumerable. 并非所有都IEnumerable可以用 索引int,所以e[0]并不总是有意义的。

这就是为什么您的代码没有多大意义。您需要将其限制为仅在 上工作IList<CustomClass<T>>,或者更具体地说,IList<CustomClass<int>>如果您想Data成为int

public static bool CustomAll<T>(this IList<CustomClass<T>> e, char symbol, int compare, Action<List<CustomClass<T>>, int, char, bool> func)
// or
public static bool CustomAll(this IList<CustomClass<int>> e, char symbol, int compare, Action<List<CustomClass<int>>, int, char, bool> func)

如果您希望它适用于 all IEnumerable<CustomClass<T>>,那么您需要使用e.First()而不是e[0](除其他外)。如果不知道CustomAll.


推荐阅读