C# 在逻辑外部声明int
昨天我只是打听一下。但是当我和你一起做这件事的时候int,它的错误C# 在逻辑外部声明int,c#,winforms,visual-studio-2008,C#,Winforms,Visual Studio 2008,昨天我只是打听一下。但是当我和你一起做这件事的时候int,它的错误 private static void mergeimagefile(string image1path, string image2path) { //get all the files in a directory string jpg1 = @image1path; string jpg2 = @image2path; string j
private static void mergeimagefile(string image1path, string image2path)
{
//get all the files in a directory
string jpg1 = @image1path;
string jpg2 = @image2path;
string jpg3 = @image2path;
Image img1 = Image.FromFile(jpg1);
Image img2 = Image.FromFile(jpg2);
//int width = img1.Width + img2.Width;
int width = 640;
//int height = Math.Max(img1.Height, img2.Height);
int height = 360;
int w;
if (img2.Width > 640) {
w = 640;
}
else if (img2.Width <= 640)
{
w = ((width - img2.Width) / 2);
}
System.Windows.Forms.MessageBox.Show(w.ToString());
int h = new int();
if (img2.Height > 360)
{
h = 360;
}
else if (img2.Height <= 360)
{
h = (height - img2.Height) / 2;
}
Bitmap img3 = new Bitmap(width, height);
Graphics g = Graphics.FromImage(img3);
g.Clear(Color.Black);
g.DrawImage(img1, new Point(0, 0));
//ERROR IN HERE
g.DrawImage(img2, new Point(w, h));
g.Dispose();
img1.Dispose();
img2.Dispose();
img3.Save(jpg3, System.Drawing.Imaging.ImageFormat.Jpeg);
img3.Dispose();
}
私有静态void mergeimagefile(字符串image1path,字符串image2path)
{
//获取目录中的所有文件
字符串jpg1=@image1path;
字符串jpg2=@image2path;
字符串jpg3=@image2path;
Image img1=Image.FromFile(jpg1);
Image img2=Image.FromFile(jpg2);
//int width=img1.width+img2.width;
整数宽度=640;
//int height=Math.Max(img1.height,img2.height);
内部高度=360;
int w;
如果(img2.Width>640){
w=640;
}
否则如果(img2.360宽度)
{
h=360;
}
否则如果(img2.Height
int w = 0;
这将解决初始化错误。您需要分配一个值,以便将其初始化为0
int w = 0;
您需要这样做的原因是如果您不匹配这些值中的任何一个
if (img2.Width > 640)
{
w = 640;
}
else if (img2.Width <= 640)
{
w = ((width - img2.Width) / 2);
}
if(img2.Width>640)
{
w=640;
}
否则,如果(img2.Widthint?w=null;表示可以赋值为null的值类型。
[在此处输入链接说明][1]为什么不直接初始化int w=0或
如果你想变得花哨,那就做吧
int w = default(int); //this is equiv to saying int w = 0;
编译器认为,w
的值在if
语句之后可能是未定义的。它没有足够聪明地认识到条件实际上涵盖了所有情况
第二个if
语句是多余的,因为如果第一个条件为false,它将始终为true。只需删除第二个if
语句,并将代码放入else
:
if (img2.Width > 640) {
w = 640;
} else {
w = ((width - img2.Width) / 2);
}
现在,编译器可以很容易地看到变量总是得到一个值。我用断点检查过。。。(img2.Width@radiaku问题是因为否则如果编译器认为两个都不匹配,w
可能是未分配的。如何使这一点正确?@radiaku使用int w=0初始化它;
查看我答案的第一行!调试之后,我发现了……一些问题我的代码背后很蠢…-————————————————————————————————————————————————————————————————————————————————————————————————————————————————————