使用未分配的变量(字符串)
我有一段迭代 XML 属性的代码:
string groupName;
do
{
switch (/* ... */)
{
case "NAME":
groupName = thisNavigator.Value;
break;
case "HINT":
// use groupName
但是这样我就得到了使用未分配变量的错误。如果我将某些内容分配给 groupName,则我无法更改它,因为这就是字符串在 C# 中的工作方式。有什么解决方法吗?
I have a piece of code that iterates over XML attributes:
string groupName;
do
{
switch (/* ... */)
{
case "NAME":
groupName = thisNavigator.Value;
break;
case "HINT":
// use groupName
But this way I get the error of using an unassigned variable. If I assign something to groupName then I cannot change it because that's how the strings work in C#. Any workarounds ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您认为 .NET 中的字符串是不可变的,这是正确的,但是您认为字符串变量无法更改的假设是错误的。
这是有效且良好的:
如果执行以下操作,您的代码将不会出现错误:
You are right that strings are immutable in .NET, but your assumption that a string variable can't be changed is wrong.
This is valid and fine:
Your code will not have an error if you do the following:
您的
switch
的default
是否为groupName
分配了值?如果不是,那么就会导致错误。Does the
default
of yourswitch
assign a value togroupName
? If not, then that will be causing the error.只需分配一个空字符串,您的应该就可以了。
Just assign an empty string and your should be okej.
编译器不知道 switch 语句的上下文(例如,不能保证 switch 始终与大小写匹配)。
因此,即使在切换之后,
groupName
也可能保持未分配状态。您可以使用
String.Empty
实例化groupName
或在 switch 语句中使用default:
。The compiler is unaware of the context of your switch statement (e.g. there's no guarantee that the switch will always match a case).
So it's possible for
groupName
to remain unassigned even after the switch.You can instantiate
groupName
withString.Empty
or usedefault:
in your switch statement.在每个 case 中设置 groupName 并在 switch 语句中使用 default 键或将 groupName 分配给 null before switch。
Set groupName in each case and use default key in switch statement or assign groupName to null before switch.