0

我正在尝试访问 using 语句之外的字符串,其值在 using 语句中分配,如下所示。

我收到错误“使用未分配的局部变量'savedUrl'”。

customItem.name = ld.Name;
customItem.Location = new GeoCoordinate(ld.Latitude, ld.Longitude, 0);
string savedUrl;
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (iso.FileExists(string.Format("{0}.jpeg", ld.Title)))
    {
        savedUrl = string.Format("{0}.jpeg", ld.Title);
    }
}
addSignPosts();
addLabel(ARHelper.AngleToVector(customItem.Bearing, WCSRadius), customItem.name, savedUrl);

如您所见,我在 using 语句之外声明了字符串“savedUrl”,以便它在 using 语句之外具有范围。但似乎在 using 语句中分配它时我无法访问它。

我尝试将其更改为全局变量。但它不起作用,这也是一种不好的做法。

那我该怎么办?我在这里错过了什么吗?

或者有什么解决方法吗?

4

3 回答 3

2

是的 - 如果iso.FileExists(string.Format("{0}.jpeg", ld.Title))返回 false 那么你将不会为savedUrl. 在这种情况下,您希望拥有什么价值savedUrl?这与声明无关using- 它if声明有关。

例如,如果您希望null文件不存在时的值,您可以反转逻辑并首先为其分配“候选”值,如果文件不存在则将其设置为 null:

string savedUrl = string.Format("{0}.jpeg", ld.Title);
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (!iso.FileExists(savedUrl))
    {
        savedUrl = null;
    }
}

或者也许使用条件运算符:

string savedUrl;
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
    string candidateUrl = string.Format("{0}.jpeg", ld.Title);
    savedUrl = iso.FileExists(candidateUrl) ? candidateUrl : null;
}

请注意,在这两个片段中,我已将代码更改为仅string.Format在一个地方调用 - 这使得以后更容易一致地更改代码。

于 2013-10-30T06:59:05.907 回答
1

尝试先给它一个初始的空字符串值,以避免错误:

string savedUrl = "";
于 2013-10-30T06:59:21.500 回答
1

您已经声明了该变量,但尚未在此处为其分配任何值。并且一个赋值在if语句中,意味着它是有条件的,并且有可能不会被赋值。因此,这是编译器的合法错误。
尝试:

string savedUrl = "";

if(!String.IsNullOrEmpty(savedUrl)
    addLabel(ARHelper.AngleToVector(customItem.Bearing, WCSRadius), customItem.name, savedUrl);
else
    // Do something here, as the variable is empty.
于 2013-10-30T06:58:39.793 回答