在以下代码的第6行出现错误

本文关键字:6行 错误 代码 | 更新日期: 2023-09-27 18:18:28

    private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
    {
        Pen graphPen = new Pen(Color.Red, 2);
        Point pt1D = new Point();
        Point pt2D = new Point();
        pt1D.X = textBox3.Text.ToString();
        e.Graphics.DrawLine(graphPen, pt1D, pt2D);
    }  

我在第6行得到错误:cannot convert type string to int.

在以下代码的第6行出现错误

其他人是正确的,您将需要转换值,但仅使用int.Parse可能会导致错误,而val = int.TryParse不是您使用int.TryParse的方式,因此,更正:

int result = 0;
if (int.TryParse(textBox3.Text, out result)) {
  pt1D.X = result;
} else {
  // input isn't an integer
}

另一件要提到的事情是Pen实现了IDisposable,所以你应该在完成使用时处理它;您可以通过显式调用Dispose或使用using:

来实现此目的。
using (Pen graphPen = new Pen(Color.Red, 2)) {
  // do what you need with the pen, 
  // it will be disposed when exiting this scope
}

您需要将文本框中的字符串转换为整数:

private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
{
    Pen graphPen = new Pen(Color.Red, 2);
    Point pt1D = new Point();
    Point pt2D = new Point();
    int xCoord = int.Parse(textBox3.Text);
    pt1D.X = xCoord;
    e.Graphics.DrawLine(graphPen, pt1D, pt2D);
}  

更改为:

private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
{
    int value = 0;
    Pen graphPen = new Pen(Color.Red, 2);
    Point pt1D = new Point();
    Point pt2D = new Point();
    pt1D.X = (int.tryParse(textBox3.Text, out value)) ? value : 0;
    e.Graphics.DrawLine(graphPen, pt1D, pt2D);
}