我有這種情況下,如果在if和else if塊中聲明相同的變量。問題在於if語句被繞過,執行移到else if語句,然後不允許重新分配變量。這是一個簡單的例子。如果,否則如果變量不更新
if (filename.ToLower().Contains(".tif"))
{
int test = 0;
string test1;
}
else if (ValidExtension(filename.ToLower()))
{
int test = 1;
//test still equals 0? Not possible right?
string test1 = "hello";
//test1 still equals null? Again not possible..?
//EDIT:
//Code that accesses test1 here, but test1 = null unless renamed to anything but test1...
}
ValidExtension只是檢查「文件名」的擴展名是否爲任何其他圖像格式,但「.tif」。它返回true或false。如果它很重要,則此代碼在GUI線程以外的其他線程上執行。
任何人都可以解釋爲什麼會發生這種可能的原因或如何發生?
編輯:
我完全理解,這些範圍內的變量我很清楚微軟的文檔。在我的編碼生涯中,我已經完成了許多其他時間,並且它工作正常。我只是有一個奇怪的例子,因爲某些原因,如果我在其下的某個代碼中使用string test1 =「hello」,仍然在Else If塊內,它會返回爲空。我對微軟文檔的理解是:test1 =「hello」,test1應該總是=「hello」,但不是,它仍然等於null。但是,如果我將代碼更改爲test2 =「hello」,那麼它實際上就是「hello」。我的問題可能措辭不佳,顯然不是很清楚。這並不意味着是一個noob問題,我想知道這將是什麼樣的錯誤呢?
編輯:
這裏是正在運行的實際代碼..希望這將提供更好的上下文的問題..
if (filename.ToLower().Contains(".tif"))
{
using (BaseBL.BeginImpersonate())
{
string output = Path.Combine(BLSettings.ClaimFilesPendingIndexingFolder, string.Format("{0}¡{1}¡{2}", "FileDrop", BaseBL.ApplicationUser, filename));
var cpyCount = 1;
while (File.Exists(output))
{
output = Path.Combine(BLSettings.ClaimFilesPendingIndexingFolder,
string.Format("{0}¡{1}¡{2}{3}.tif", "FileDrop", BaseBL.ApplicationUser, filename.Replace(".tif", string.Empty),
cpyCount));
cpyCount++;
}
var f = File.Create(output);
f.Write(file.ToArray(), 0, int.Parse(file.Length.ToString()));
f.Close();
f.Dispose();
}
}
else if (ValidExtension(filename.ToLower()))
{
var image = new Bitmap(file);
string output = Path.Combine(BLSettings.ClaimFilesPendingIndexingFolder, string.Format("{0}¡{1}¡{2}.tif", "FileDrop", BaseBL.ApplicationUser, Path.GetFileNameWithoutExtension(filename)));
//output = null always. If changed to output1 it contains the valid filepath...??
var cpyCount = 1;
while (File.Exists(output))
{
output = Path.Combine(BLSettings.ClaimFilesPendingIndexingFolder,
string.Format("{0}¡{1}¡{2}{3}.tif", "FileDrop", BaseBL.ApplicationUser, Path.GetFileNameWithoutExtension(filename),
cpyCount));
cpyCount++;
}
using (BaseBL.BeginImpersonate())
image.Save(output, ImageFormat.Tiff);
image.Dispose();
}
您的變量僅在範圍'{...}'它們被定義可見。 – Habib
您不適合觀察程序,而不是程序不正確。 – Servy
@Bathsheba好吧,考慮到幾分鐘內有4個答案,而且在我看來,他們每個人都錯誤地解釋了這個問題,這意味着問題根本不明確。這是降低它的可接受的理由。 – Servy