3 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
編譯器要求bar在使用它之前將其設(shè)置為某個(gè)值,并且由于someFlag可能在您的if塊之間進(jìn)行更改(這意味著第一個(gè)塊可能無(wú)法運(yùn)行,而第二個(gè)塊可能會(huì)運(yùn)行),因此它將給您帶來(lái)錯(cuò)誤。為避免這種情況,您可以最初將bar設(shè)置為默認(rèn)值:
Bar bar = default(Bar); // this will be 'null' for class objects
然后您的其余代碼應(yīng)按預(yù)期工作
const bool someFlag = foo.SomeFlag;
if (someFlag)
{
// Do something, assign bar to new value
bar = new Bar();
}
// Do some other stuff
// Possibly add a check that bar was set, just to be safe...
if (someFlag && bar != null)
{
// Use bar
bar.DoSomething();
}

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
欺騙編譯器允許這樣做意味著您的解決方案將有機(jī)會(huì)出現(xiàn)異常。
想想,如果foo.SomeFlag不正確怎么辦?bar的值將為null,或更具體地說(shuō),它將為default(Bar)。(是的,編譯器知道任何類(lèi)型的默認(rèn)值是什么)。如果按照我的想法,Bar是一個(gè)類(lèi),則該值肯定為null。然后當(dāng)它嘗試使用bar時(shí),假設(shè)您嘗試使用bar,它會(huì)引發(fā)異常。編譯器實(shí)際上是在保護(hù)您免受它侵害。
解決的方法只是在使用bar之前進(jìn)行空檢查。喜歡:
if (someFlag)
{
if(bar != null)
{
// use bar
}
}
盡管如此,我強(qiáng)烈建議您開(kāi)始初始化變量,這樣您就可以肯定并且不會(huì)忘記。喜歡:
解決方案1:用一些東西開(kāi)始吧。
Bar bar = null; // <- Only if you know for sure Bar is a class
// or
Bar bar = default(Bar);
if (foo.SomeFlag)
{
...
}
解決方案2:另辟else徑
if (foo.SomeFlag)
{
...
}
else
{
bar = null; // <- Only if you know for sure Bar is a class
// or
bar = default(bar);
}
...

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
編譯器不夠智能,無(wú)法識(shí)別您的if塊是否將被實(shí)際執(zhí)行。因此,它假定bar在使用之前可能無(wú)法初始化。為了減輕這種情況,只需將bar初始值設(shè)置為null或提供一條else語(yǔ)句即可。
Bar bar = null;
const bool someFlag = foo.SomeFlag;
if (someFlag)
{
// ... do stuff
bar = .. // set bar, guaranteed unless exception thrown earlier in this block
}
// do other stuff
if (someFlag)
{
// use bar
}
或者:
Bar bar;
const bool someFlag = foo.SomeFlag;
if (someFlag)
{
// ... do stuff
bar = .. // set bar, guaranteed unless exception thrown earlier in this block
}
else
{
bar = null;
}
// do other stuff
if (someFlag)
{
// use bar
}
- 3 回答
- 0 關(guān)注
- 143 瀏覽
添加回答
舉報(bào)