【问题标题】:Replace string value in C#? [closed]在 C# 中替换字符串值? [关闭]
【发布时间】:2014-07-13 20:54:23
【问题描述】:

我是 C# 新手,需要一点帮助,我知道在 PHP 中我可以做到这样的事情

$SelectedEvent="event selected";

if (i > 0)
{
  $SelectedEvent = "event";
}

它很容易替换字符串,但在 c# 中无法正常工作,这是我的示例代码,但无法正常工作

  string SelectedEvent = "event selected"; 

  if (i > 0)
    {
         SelectedEvent = "event"; 
    }

这不像在 PHP 中那样工作,我不能覆盖变量?

这是我的示例代码

已编辑

for (int i = 0; i < Model.Items.Count; i++)
{

    string SelectedEvent = "event selected";    


    if (i > 1)
    {
         string SelectedEvent = "event"; 
    }

}

【问题讨论】:

  • 这应该可以了,i的值是多少?
  • 它确实有效,是什么让您认为它无效?
  • 这不是替换!顺便说一句,它应该工作!
  • 刚刚为你做了小提琴:dotnetfiddle.net/Ac7i5t
  • 您在 if 块中声明了一个与第一个变量同名的新变量,从而有效地掩盖了外部变量

标签: c# string replace


【解决方案1】:

你不应该重新声明变量两次,而只修改它的值:

for (int i = 0; i < Model.Items.Count; i++)
{
    string SelectedEvent = "event selected";    
    if (i > 1)
    {
         SelectedEvent = "event"; 
    }

    // here you can use the SelectedEventVariable
    // its value will be "event selected" on the first and second
    // iterations and "event" on subsequent 
}

【讨论】:

  • Txanks 现在没问题,正如我所说我是 C# 新手
  • 只是好奇——@ 符号是干什么用的?
  • @adv12,它在 OP 中。我猜这是在 Razor 模板中,他的问题被错误地标记为 C#。
  • 是的,我忘了删除它,因为它是非常复杂的代码,只有我需要这部分,txanks
猜你喜欢
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
  • 2012-12-11
  • 2012-06-18
  • 2014-03-06
  • 2021-12-16
  • 2013-03-08
相关资源
最近更新 更多