【问题标题】:Use of unassigned variable (string)使用未分配的变量(字符串)
【发布时间】:2011-12-04 19:44:14
【问题描述】:
我有一段代码遍历 XML 属性:
string groupName;
do
{
switch (/* ... */)
{
case "NAME":
groupName = thisNavigator.Value;
break;
case "HINT":
// use groupName
但是这样我得到了使用未分配变量的错误。如果我为 groupName 分配了一些东西,那么我无法更改它,因为这就是字符串在 C# 中的工作方式。有什么解决方法吗?
【问题讨论】:
标签:
c#
string
unassigned-variable
【解决方案1】:
strings 在 .NET 中是不可变的,这是对的,但你认为字符串 variable 不能更改的假设是错误的。
这是有效且没问题的:
string groupName = null;
groupName = "aName";
groupName = "a different Name";
如果您执行以下操作,您的代码将不会出错:
string groupName = string.Empty; // or null, if empty is meaningful
do
{
switch (/* ... */)
{
case "NAME":
groupName = thisNavigator.Value;
break;
case "HINT":
// use groupName
【解决方案2】:
您的switch 的default 是否为groupName 赋值?如果不是,那么这将导致错误。
switch
{
case "NAME":
groupName = thisNavigator.Value;
break;
//...
default:
groupName = "something";
break;
}
【解决方案3】:
string groupName = string.Empty;
只需分配一个空字符串,你就可以了。
【解决方案4】:
编译器不知道你的 switch 语句的上下文(例如,不能保证 switch 总是匹配大小写)。
因此,即使在切换之后,groupName 也可能保持未分配状态。
您可以使用String.Empty 实例化groupName 或在您的switch 语句中使用default:。
【解决方案5】:
在每个 case 中设置 groupName 并在 switch 语句中使用 default 键或将 groupName 分配给 null before switch。