3

The best way to illustrate my question is this C# example:

//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";

Can I do this in C#?

PS. I know that I can do this in a function. I'm asking about an "in-line" approach.

4

3 回答 3

2

如果你真的想做类似于你要求的方式的任务,这里是一种不使用 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 纳秒。两者都不可能成为重要的瓶颈。

于 2013-11-06T00:45:26.317 回答
1

你为什么要把它分成一个开关,然后再分配一个?为什么不直接在 switch 中设置值并完全避免 ref 行为呢?

string newValue = "new value";

switch(type)
{
    case 0:
        someString0 = newValue;
        break;
    case 1:
        someString1 = newValue;
        break;
    //And so on

    default:
        someStringN = newValue;
        break;
}
于 2013-11-06T00:29:27.277 回答
0

为什么不像这样设置正确的字符串变量:

switch(type)
{
    case 0:
        someString0 = "New Value";
        break;
    case 1:
        someString1 = "New Value";
        break;
    //And so on

    default:
        someStringN = "New Value";
        break;
}

一个更好的方法是用一个字符串数组替换你的 n 个字符串变量,这样赋值就变成了一行代码:

string[] someString;
someString[type] = "New Value";
于 2013-11-06T00:30:47.860 回答