How to make a reference to a struct in C#
in my application I have a LineShape control and a custom control (essentially a PictureBox with Label).
I want the LineShape to change one of its points coordinates, according to location of the custom control.
I had an idea to set a reference to a LineShape point inside the custom control and add location change event handler that chan开发者_如何学编程ges referenced point coordinates.
However built in Point is a struct which is a value type, so that won't work. Does anyone have idea, how to make a reference to a structure or maybe someone knows a workaround for my problem?
I tried the solution regarding usage of the nullable type but it still doesn't work. Here's the way I define the field in my custom control (DeviceControl):
private Point? mConnectionPoint;
And implementation of the location change event handler:
private void DeviceControl_LocationChanged(object sender, EventArgs e)
{
if (mConnectionPoint != null)
{
DeviceControl control = (DeviceControl)sender;
Point centerPoint= new Point();
centerPoint.X = control.Location.X + control.Width / 2;
centerPoint.Y = control.Location.Y + control.Height / 2;
mConnectionPoint = centerPoint;
}
}
You can pass value types by reference by adding 'ref' before it when passing in a method.
like this:
void method(ref MyStruct param)
{
}
Your method does not really require 'reference' access to the mConnectionPoint member; You can assign the location values directly to the referenced Point, as a member of your class:
private void DeviceControl_LocationChanged(object sender, EventArgs e)
{
if (mConnectionPoint != null)
{
DeviceControl control = (DeviceControl)sender;
mConnectionPoint.X = control.Location.X + control.Width / 2;
mConnectionPoint.Y = control.Location.Y + control.Height / 2;
}
}
However, if the reason for this code is to move the LineShape control, then you should go straight to the source. The best way to change the properties of a control is just to change the properties on the control:
DeviceControl control = (DeviceControl)sender;
line1.StartPoint = [calculate point1 coordinates];
line1.EndPoint = [calculate point2 coordinates];
精彩评论