c# - 如何在 C# 中声明字符串引用变量?

标签 c# .net

说明我的问题的最佳方式是这个 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/

相关文章:

c# - 跟踪代码随时间的变化

c# - TreeView 全路径剥离

c# - 向自定义异常添加额外信息

c# - dot.Net 委托(delegate)有多少种方法?

c# - 使用 .NET 进行多线程文件处理

c# - 如何在几秒钟后更改标签文本?

c# - 将所有子节点作为 Json 返回动态对象 - 错误 : cannot use a lambda expression as an argument to a dynamically dispatched

c# - DataContext.CreateDatabase 正在创建具有随机顺序列的数据库

c# - Entity Framework 存储过程单一结果集

c# .NET multipart/form-data 上传文件