如何在 C# 中获取字符串属性的引用
假设我有一个具有三个字符串属性的类:
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.";
这不起作用。我知道这与字符串不变性有关(至少我认为确实如此),但我不知道该怎么做。
弦乐基本上让我感到困惑。
嗯,是的,所以我的问题是最简洁的方法是什么?
Say I have a class with three string properties:
public class Foo
{
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
}
Now say I want to assign to one of the string properties, but that which of the three properties I assign to depends upon some condition. Knowing that strings are supposedly reference types, I might be tempted to write some code like this:
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.";
This doesn't work. I know it's got something to do with string immutability (at least I think it does) but I haven't any idea how to do it.
Strings basically confuse the bejesus out of me.
Um, yeah, so my question is what's the most concise way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就我个人而言,我可能会继续分配属性:
如果您真的想要使用您建议的方法,您可以将其包装在委托中,我猜:
......但在这种情况下,这只会让事情变得不必要的复杂。对于问题中描述的场景,我想不出您想要这样做的任何原因。
Personally I would probably just go ahead and assign the property:
If you really want to use the approach you suggest, you can wrap it in a delegate I guess:
...but in this case that would only make things unnecessarily complex. For the kind of scenario that is described in the question, I can't think of any reason you would want to do this.
就这样做:
C# 尝试使字符串尽可能易于使用。它们是原始类型,因此您实际上不需要担心可变性、内存、地址或类似的问题。
Just do it like this:
C# tries to make strings as easy as possible to work with. They are primitive types, so you don't really need to worry about mutability or memory or addresses or anything like that.
您始终可以这样做:
EDITED **
var someString = (condition1) ? foo.Bar1 : (条件2) ? foo.Bar2 : (条件3) ? foo.Bar3:“戴夫,我做不到”;
让我知道你进展如何。
You can always do it like this:
EDITED **
var someString = (condition1) ? foo.Bar1 : (condition2) ? foo.Bar2 : (condition3) ? foo.Bar3 : "I can't do that Dave";
Let me know how you go.