说明我的问题的最佳方式是这个 C# 示例:
//It seems that the comment is required:
//I need to change the values of someString0, someString1, or someStringN
//depending on the `type` variable
ref string strKey;
switch(type)
{
case 0:
strKey = ref someString0;
break;
case 1:
strKey = ref someString1;
break;
//And so on
default:
strKey = ref someStringN;
break;
}
//Set string
strKey = "New Value";
我可以在 C# 中执行此操作吗?
附言。我知道我可以在函数中做到这一点。我问的是“在线”方法。
最佳答案
如果你真的想按照你要求的方式进行分配,这里有一种不使用 ref 的方法
Action<string> action;
switch (type) {
case 0:
action = newVal => someString0 = newVal;
break;
case 1:
action = newVal => someString1 = newVal;
break;
case 2:
action = newVal => someString2 = newVal;
break;
default:
action = null;
break;
}
if (action != null) action.Invoke("some new value");
在性能方面,上面的执行时间比下面的直接替代方案长大约 8 纳秒
switch (i) {
case 0:
someString0 = "some new value";
break;
case 1:
someString1 = "some new value";
break;
case 2:
someString2 = "some new value";
break;
default:
break;
}
但是你说的比几乎没有的时间要长一点。在我速度不是特别快的笔记本电脑上,Action 版本执行大约需要 13 纳秒,而直接赋值方法大约需要 5.5 纳秒。两者都不太可能成为重要的瓶颈。
关于c# - 如何在 C# 中声明字符串引用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19801670/