如何在C#中获取对字符串属性的引用

时间:2011-02-24 22:29:45

标签: c# string immutability

假设我有一个包含三个字符串属性的类:

public class Foo
{
  public string Bar1 { get; set; }
  public string Bar2 { get; set; }
  public string Bar3 { get; set; }
}

现在说我要分配给其中一个字符串属性,但是我指定的三个属性中的哪一个取决于某些条件。知道字符串应该是引用类型,我可能想写一些像这样的代码:

string someString;
if (condition1) someString = foo.Bar1;
else if (condition2) someString = foo.Bar2;
else if (condition3) someString = foo.Bar3;
someString = "I can't do that, Dave.";

这不起作用。我知道它与字符串不变性有关(至少我认为它确实如此)但我不知道该怎么做。

字符串基本上混淆了bejesus。

嗯,是的,所以我的问题是最简洁的方法是什么?

3 个答案:

答案 0 :(得分:2)

就这样做:

string someString = "I can't do that, Dave.";
if (condition1) foo.Bar1 = someString;
else if (condition2) foo.Bar2 = someString;
else if (condition3) foo.Bar3 = someString;

C#尝试使字符串尽可能简单易用。它们是原始类型,因此您不必担心可变性或内存或地址或类似的东西。

答案 1 :(得分:2)

我个人可能会继续分配财产:

string value = "I can't do that, Dave.";
if (condition1) foo.Bar1 = value;
else if (condition2) foo.Bar2 = value;
else if (condition3) foo.Bar3 = value;

如果确实想要使用您建议的方法,我可以将其包装在委托中:

Action<string> assignString;
if (condition1) assignString = s => foo.Bar1 = s;
else if (condition2) assignString = s => foo.Bar2 = s;
else if (condition3) assignString = s => foo.Bar3 = s;
assignString("I can't do that, Dave.");

...但在这种情况下,只会使事情变得不必要地复杂化。对于问题中描述的那种场景,我想不出你想要这样做的任何理由。

答案 2 :(得分:0)

你可以这样做:

编辑**

var someString =(condition1)? foo.Bar1 :(条件2)? foo.Bar2 :(条件3)? foo.Bar3:“我不能那样做Dave”;

让我知道你怎么走。