声明int外部逻辑

问题描述:

昨天我只是问了一下logic, if else error。但是当我这样做? INT,其错误...声明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;,并根据this Msdn Manual,它还是给了我错误?

错误1使用未分配的局部变量的 'W' C:\ Documents和Settings \ ADMIN \我的文档\ Visual Studio 2008的\项目\模板\模板\ Form1.cs中68 50模板

如何做到这一点?

您需要分配一个值,它初始化为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();不是您用来初始化整数的方法。

+0

我使用断点检查...(img2.Width radiaku

+0

@radiaku问题是因为'else if'编译器认为'if'匹配是可能的,'w'将是未分配的。 –

+0

以及如何使其正确? – radiaku

如何

int w = 0; 

这应该照顾初始化errror的。

+0

但价值保持不变?任何手? – radiaku

+0

您的代码看起来正确,但不必要的复杂。我建议在初始化期间将w的值设置为640,然后使用第二个if语句 –

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语句是多余的,因为如果第一个条件为false,它将始终为真。只是删除第二if语句,并把代码中的else

if (img2.Width > 640) { 
    w = 640; 
} else { 
    w = ((width - img2.Width)/2); 
} 

现在,编译器可以很容易地看到变量总是得到的值。