C#if else逻辑错误

rad*_*aku 1 c# winforms

我做了一些逻辑,但它的错误?

我的代码

private static void DrawText(String text, Font font, Color textColor, Color backColor)
{
    Image img = new Bitmap(640, 360);
    Graphics drawing = Graphics.FromImage(img);

    Color color = textColor;
    if (text.Length <= 80) {
        Rectangle displayRectangle =
            new Rectangle(new Point(20, 100), new Size(img.Width - 1, img.Height - 1));
    } else {
        Rectangle displayRectangle =
            new Rectangle(new Point(20, 80), new Size(img.Width - 1, img.Height - 1));
    }
    StringFormat format1 = new StringFormat(StringFormatFlags.NoClip);
    StringFormat format2 = new StringFormat(format1);

     // ERROR ON NEXT LINE
    drawing.DrawString(text, font, Brushes.Red, (RectangleF)displayRectangle, format2);

    drawing.Dispose();
    string fileName = "f.png";
    string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
    img.Save(path, System.Drawing.Imaging.ImageFormat.Png);

    img.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

错误是

错误1当前上下文中不存在名称"displayRectangle"C:\ Documents and Settings\admin\My Documents\Visual Studio 2008>\Projects\template\template\Form1.cs 119 69模板

在这条线上

drawing.DrawString(text, font, Brushes.Red, (RectangleF)displayRectangle, format2);
Run Code Online (Sandbox Code Playgroud)

在php中,逻辑是正确的,但是当在C#中获取错误时,如何在C#中执行此逻辑?

有帮助吗?(仍在学习C#:D)

COL*_*OLD 12

Rectangle定义移到if else块上方,这样它就不会超出范围.

Rectangle displayRectangle;

if (text.Length <= 80)
{
    displayRectangle = new Rectangle(new Point(20, 100), new Size(img.Width  img.Height - 1));
}
else
{
    displayRectangle = new Rectangle(new Point(20, 80), new Size(img.Width -  img.Height - 1));
}
Run Code Online (Sandbox Code Playgroud)


SWe*_*eko 5

基本上,它不起作用:)

在一个if或一个else块内,在{和之间定义的变量}仅在该块中可见.这就是为什么你能够定义它两次,一次在if分支中,一次在else分支中.

因此解决方案是在分支之前声明变量,并将其设置在if/else分支中.

Rectangle displayRectangle; //declaration

if (text.Length <= 80)
{
  //setting
  displayRectangle = new Rectangle(new Point(20, 100), new Size(img.Width - 1, img.Height - 1));
}
else
{
  //setting
  displayRectangle = new Rectangle(new Point(20, 80), new Size(img.Width - 1, img.Height - 1));
}
....
//usage
drawing.DrawString(text, font, Brushes.Red, (RectangleF)displayRectangle, format2);
Run Code Online (Sandbox Code Playgroud)

此外,C#编译器足够智能,可以检测到每个分支中都设置了变量,因此当它到达它的使用代码时肯定会被设置.但是,如果没有在每个分支中设置,那将是编译错误,例如

if (text.Length <= 80)
{
  displayRectangle = ...;
}
else if (text.Length > 40)
{

  displayRectangle = ...;
}
Run Code Online (Sandbox Code Playgroud)