c# - 为什么在使用 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;
}
解决方案
请注意,您的扩展方法也适用于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
.
推荐阅读
- ansible - 从 Ansible Tower (awx) 执行的 fetch_module 故障排除
- javascript - Webpack 在 dist 文件夹上保留文件夹结构
- python - 用用户输入填充字典的说明
- c# - M1 MacBook Air 上的 Rider 无法解析符号
- material-ui - 如何删除 DataGrid 中焦点的轮廓
- typescript - 如何在样式化的第三方组件上使用道具?
- vba - 如果表中的数据发生更改,如何更新?
- r - 使用具有重复类别的 ggplot 重新排序条形图
- java - WSL2(Windows 10)上的 minikube - minikube ip 无法访问
- reactjs - 从 JSX 花括号返回函数