声明int外部逻辑
本文关键字:外部 int 声明 | 更新日期: 2023-09-27 17:49:47
昨天我只是问逻辑,如果否则错误。但是当我这样做的时候?int,它的错误…
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();
}
我试过添加,int?
, int w = null;
,根据这个Msdn手册,它仍然给我错误?
错误1使用未分配的局部变量'w' C:'Documents and Settings'admin'My Documents'Visual Studio 2008'Projects'template'template'Form1.cs 68 50 template
如何使这个正确?
int w = 0;
初始化错误处理
你需要分配一个值,初始化为0。
int w = 0;
你需要这样做的原因是,如果你不匹配这些值
if (img2.Width > 640)
{
w = 640;
}
else if (img2.Width <= 640)
{
w = ((width - img2.Width) / 2);
}
则w
将被取消分配。
也以同样的方式分配h
,因为int h = new int();
不是用于初始化整数的方法。
int? w = null; Represents a value type that can be assigned null.
[输入链接描述在这里][1]为什么不直接初始化int w = 0或
如果你想要花哨的,做
int w = default(int); //this is equiv to saying int w = 0;
编译器认为w
的值在if
语句之后可能没有定义。它还不够聪明,无法识别这些条件实际上涵盖了所有情况。
第二个if
语句是多余的,因为如果第一个条件为假,它总是为真。只需删除第二个if
语句,并将代码放入else
:
if (img2.Width > 640) {
w = 640;
} else {
w = ((width - img2.Width) / 2);
}
现在编译器可以很容易地看到变量总是得到一个值