gpt4 book ai didi

C# if else逻辑错误

转载 作者:太空宇宙 更新时间:2023-11-03 17:07:25 24 4
gpt4 key购买 nike

我在做某种逻辑但出现错误?

这里是我的代码

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

错误是

Error 1 The name 'displayRectangle' does not exist in the current context C:\Documents and Settings\admin\My Documents\Visual Studio 2008>\Projects\template\template\Form1.cs 119 69 template

在这一行

drawing.DrawString(text, font, Brushes.Red, (RectangleF)displayRectangle, format2);

在 php 中逻辑是正确的,但是在 C# 中却出现错误?,如何在 C# 中执行此逻辑?

有什么帮助吗? (仍在通过实践学习 C# :D )

最佳答案

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

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

关于C# if else逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14076171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com