-1

昨日、ロジックについて質問しました。それ以外の場合はエラーです。しかし、私がこれを行うときは?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?このMsdnマニュアルint w = null;によると、それでもエラーが発生しますか?

エラー1割り当てられていないローカル変数'w'の使用C:\ Documents and Settings \ admin \ My Documents \ Visual Studio 2008 \ Projects \ template \ template \ Form1.cs6850テンプレート

これを正しくする方法は?

4

4 に答える 4

2

どうですか

int w = 0;

これにより、初期化エラーが処理されます。

于 2012-12-29T18:00:36.317 に答える
1

値を割り当てる必要があるため、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();

于 2012-12-29T18:01:13.033 に答える
1

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;
于 2012-12-29T18:10:42.633 に答える
0

コンパイラは、ステートメントwの後に の値が未定義になる可能性があると考えます。if条件が実際にすべての状況をカバーしていることを認識するほど賢くは構築されていません。

if最初の条件が false の場合は常に true になるため、2 番目のステートメントは不要です。2 番目のステートメントを削除してif、コードをelse:

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

これで、コンパイラは、変数が常に値を取得することを簡単に確認できます。

于 2012-12-29T18:25:32.137 に答える