C# 如何在C中引用结构#

C# 如何在C中引用结构#,c#,reference,struct,C#,Reference,Struct,在我的应用程序中,我有一个LineShape控件和一个自定义控件(基本上是一个带标签的PictureBox) 我希望线型根据自定义控件的位置更改其一个点坐标 我想在自定义控件内设置对线型点的引用,并添加更改引用点坐标的位置更改事件处理程序 然而,内置点是一个值类型的结构,所以这不起作用。有人知道如何引用结构吗?或者有人知道我的问题的解决方法吗 我尝试了使用可空类型的解决方案,但仍然不起作用。以下是我在自定义控件(DeviceControl)中定义字段的方式: 和位置更改事件处理程序的实现: pr

在我的应用程序中,我有一个LineShape控件和一个自定义控件(基本上是一个带标签的PictureBox)

我希望线型根据自定义控件的位置更改其一个点坐标

我想在自定义控件内设置对线型点的引用,并添加更改引用点坐标的位置更改事件处理程序

然而,内置点是一个值类型的结构,所以这不起作用。有人知道如何引用结构吗?或者有人知道我的问题的解决方法吗

我尝试了使用可空类型的解决方案,但仍然不起作用。以下是我在自定义控件(DeviceControl)中定义字段的方式:

和位置更改事件处理程序的实现:

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;
    }
}

传入方法时,可以通过在值类型之前添加“ref”来通过引用传递值类型

像这样:

void method(ref MyStruct param)
{
}

您的方法实际上不需要对mConnectionPoint成员进行“引用”访问;可以将位置值作为类的成员直接指定给参照点:

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;
    }
}
但是,如果此代码的原因是要移动线型控件,则应直接转到源代码。更改控件属性的最佳方法就是更改控件的属性:

    DeviceControl control = (DeviceControl)sender;

    line1.StartPoint = [calculate point1 coordinates];
    line1.EndPoint = [calculate point2 coordinates];
    DeviceControl control = (DeviceControl)sender;

    line1.StartPoint = [calculate point1 coordinates];
    line1.EndPoint = [calculate point2 coordinates];