c# - 使用未分配的变量(字符串)

标签 c# string unassigned-variable

我有一段迭代 XML 属性的代码:

string groupName;
do
{
    switch (/* ... */)
    {
        case "NAME":
            groupName = thisNavigator.Value;
            break;
        case "HINT":
            // use groupName

但是这样我得到了使用未分配变量的错误。如果我将某些内容分配给 groupName,则我无法更改它,因为这就是字符串在 C# 中的工作方式。任何解决方法?

最佳答案

字符串 在 .NET 中是不可变的,你是对的,但你认为字符串变量 不能更改的假设是错误的。

这是有效的并且没问题:

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

关于c# - 使用未分配的变量(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8378070/

相关文章:

c# - Entity Framework 多态关联

c# - ListBox 不断将选定的索引返回为 -1

c# - 在 C# 中使用 MakeGenericMethod 后如何制作具体类型?

javascript - 在 for 循环中时,Jquery 赋值失败

c# - C# 中的存在类型?

r - 删除分隔符内的字符串部分

python - 打破Python字符串内的for循环 join() 方法

string - 如何构造具有多个具有不同生命周期的str变量的结构?

c# - 编译器错误说我没有分配局部变量并且名称在当前上下文中不存在,而它确实存在?

c#开关问题