【发布时间】:2018-08-24 00:18:09
【问题描述】:
我在 ObservableCollection 上为自定义类型创建扩展方法时遇到问题。我需要创建的扩展方法是“ToAnotherType”类型(如 ToList、ToArray)。 MyPoint 示例实现了 IEnumerable 接口,但我认为我没有正确公开 yield?
真实的事情显然有更多的事情发生,这只是控制台应用程序中的一个精简示例,用于识别问题。我尝试将 OC 更改为常规 List 以查看那里是否发生了某些事情,但事实并非如此。
我看到许多“如何使您的类可枚举”示例创建从 List 派生的第二个类(IE,公共类 MyPointList : List),但是当原始类型可以自己处理它或让它被推送时,这似乎很浪费在部分类文件中关闭。
这一切看起来都在工作,直到扩展方法本身中的 foreach - 我得到一个错误,说“MyPoint”不包含“X”和“Y”的定义。
我显然可以使用一个接收 List 并返回一个 List 的方法来处理转换,但如果有扩展名,那就太好了。
关于我如何完成我所做的代码的参考: https://www.codeproject.com/Articles/474678/A-Beginners-Tutorial-on-Implementing-IEnumerable-I
https://dotnetcodr.com/2015/07/24/implementing-an-enumerator-for-a-custom-object-in-net-c/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Collections;
namespace EnumerableDemo
{
class Program
{
static void Main(string[] args)
{
var myPoints = new ObservableCollection<MyPoint>
{
new MyPoint(10, 10),
new MyPoint(20, 20),
new MyPoint(30, 30),
new MyPoint(40, 40),
new MyPoint(50, 50)
};
Console.WriteLine("Print a single point via extension method:");
PrintSinglePointToConsole(myPoints[0].ToPoint());
Console.WriteLine("");
Console.WriteLine("Print the whole OC of points:");
PrintPointsToConsole(myPoints.ToPoints());
Console.ReadLine();
}
public static void PrintSinglePointToConsole(Point point)
{
Console.WriteLine("Point {0},{1}", point.X, point.Y);
}
public static void PrintPointsToConsole(List<Point> points)
{
foreach (var item in points)
{
Console.WriteLine("Point: {0},{1}", item.X, item.Y);
}
}
}
public class MyPoint : IEnumerable<MyPoint>
{
private List<MyPoint> _myPoints = new List<MyPoint>();
private int _x { get; set; } = 0;
public int X { get { return _x; } set { _x = value; } }
private int _y { get; set; } = 0;
public int Y { get { return _y; } set { _y = value; } }
public MyPoint()
{
}
public MyPoint(int x, int y)
{
_x = x;
_y = y;
}
public IEnumerator<MyPoint> GetEnumerator()
{
foreach (var item in _myPoints)
{
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public static class MyPointExtension
{
public static Point ToPoint(this MyPoint point)
{
return new Point(point.X, point.Y);
}
public static List<Point> ToPoints<MyPoint>(this ObservableCollection<MyPoint> list)
{
var result = new List<Point>();
foreach (var item in list)
{
//Line with error:
//'MyPoint' Does not contain a definition for 'X' and no extension method for
//'X' accepting a first argument type of 'MyPoint' could be found.
result.Add(new Point(item.X, item.Y));
}
return result;
}
}
}
【问题讨论】:
标签: c#