c# - ArrayList object to array of Point objects -
i have custom class curvepoint
define set of data items draw on screen using drawcurve
i written cast routine convert curvepoint point, getting error at least 1 element in source array not cast down destination array type. when try use .toarray method in arraylist
i can cast objects fine using code:
point f = new curvepoint(.5f, .5f, new rectangle(0, 0, 10, 10));
but if fails when using
point[] plots=(point[])_data.toarray(typeof(point));
(where _data arraylist populated 5 curvepoint objects)
here full code:
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 curvepoint) { curvepoint cp = (curvepoint)obj; return plotx.compareto(cp.plotx); } else { throw new argumentexception("object not 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%"); } }
can sujest how fix code?
first, change arraylist typed generic list, list<curvepoint>
. then, point array, can perform code.
point[] plots = _data.select(obj => (point)obj).toarray();
if leave arraylist, can still using code:
point[] plots = (from curvepoint obj in _data select (point)obj).toarray(); // or point[] plots = _data.cast<curvepoint>().select(obj => (point)obj).toarray();
edit: finally, if you're stuck arraylist and not have linq, can "long" way.
point[] plots = new point[_data.count]; (int = 0; < _data.count; i++) { plots[i] = (point)(curvepoint)_data[i]; }
Comments
Post a Comment