【发布时间】:2011-04-22 12:19:26
【问题描述】:
我有一个自定义类CurvePoint,我使用DrawCurve 定义了一组要在屏幕上绘制的数据项
我编写了一个转换例程来将 CurvePoint 转换为 Point,但出现错误 源数组中的至少一个元素无法转换为目标数组类型。当我尝试在 Arraylist 中使用 .ToArray 方法时
我可以使用代码很好地投射对象:
Point f = new CurvePoint(.5F, .5F, new Rectangle(0, 0, 10, 10));
但是如果使用时失败
Point[] Plots=(Point[])_Data.ToArray(typeof(Point));
(其中 _Data 是一个 ArrayList,其中填充了 5 个 CurvePoint 对象)
这里是完整的代码:
public partial class Chart : UserControl
{
ArrayList _Data;
public Chart()
{
InitializeComponent();
_Data = new ArrayList();
_Data.Add(new CurvePoint(0f, 0f,this.ClientRectangle));
_Data.Add(new CurvePoint(1f, 1f, this.ClientRectangle));
_Data.Add(new CurvePoint(.25f, .75f, this.ClientRectangle));
_Data.Add(new CurvePoint(.75f, .25f, this.ClientRectangle));
_Data.Add(new CurvePoint(.5f, .6f, this.ClientRectangle));
}
private void Chart_Paint(object sender, PaintEventArgs e)
{
_Data.Sort();
e.Graphics.FillEllipse(new SolidBrush(Color.Red),this.ClientRectangle);
Point[] Plots=(Point[])_Data.ToArray(typeof(Point));
e.Graphics.DrawCurve(new Pen(new SolidBrush(Color.Black)), Plots);
}
}
public class CurvePoint : IComparable
{
public float PlotX;
public float PlotY;
public Rectangle BoundingBox;
public CurvePoint(float x, float y,Rectangle rect)
{
PlotX = x; PlotY = y;
BoundingBox = rect;
}
public int CompareTo(object obj)
{
if (obj is CurvePoint)
{
CurvePoint cp = (CurvePoint)obj;
return PlotX.CompareTo(cp.PlotX);
}
else
{ throw new ArgumentException("Object is not a CurvePoint."); }
}
public static implicit operator Point(CurvePoint x)
{
return new Point((int)(x.PlotX * x.BoundingBox.Width), (int)(x.PlotY * x.BoundingBox.Height));
}
public static implicit operator string(CurvePoint x)
{
return x.ToString();
}
public override string ToString()
{
return "X=" + PlotX.ToString("0.0%") + " Y" + PlotY.ToString("0.0%");
}
}
任何人都可以解决如何修复代码吗?
【问题讨论】: