C# if else 逻辑错误 [英] C# if else logic error
问题描述
我做了某种逻辑,但出现错误?
I doing some kind logic but its getting error?
这里是我的代码
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();
}
错误是
错误 1 当前上下文中不存在名称displayRectangle" C:\Documents and Settings\admin\My Documents\Visual Studio 2008>\Projects\template\template\Form1.cs 119 69 模板
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# 中执行此逻辑?
In php the logic was right, but when in C# its getting error?, How doing this logic in C#?
有什么帮助吗?(仍在通过做 :D 学习 C#)
Any help? ( Still learning C# by doing :D )
推荐答案
基本上,它不会那样工作 :)
Basically, it doesn't work that way :)
在 if
或 else
块中定义的变量,在 {
和 }
之间只可见在那个街区.这就是为什么您能够定义它两次,一次在 if
分支中,一次在 else
分支中.
Variables defined within an if
or an else
block, between the {
and the }
are only visible in that block. That is why you were able to define it twice, once in the if
branch and once in the else
branch.
所以解决方案是在分支前声明变量,在if/else分支中设置即可.
So the solution is to declare the variable before the branching, and just set it in the if/else branches.
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);
此外,C# 编译器足够智能,可以检测到每个分支中设置的变量,因此当它到达使用代码时肯定会设置它.但是,如果不是在每个分支中都设置它,那将是一个编译错误,例如
In addition, the C# compiler is smart enough to detect that the variable is set in each branch, so that it will definitely be set when it reaches it's usage code. However, if it's not set in every branch, that would be a compile error, e.g.
if (text.Length <= 80)
{
displayRectangle = ...;
}
else if (text.Length > 40)
{
displayRectangle = ...;
}
这篇关于C# if else 逻辑错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!