无法将属性或索引器'string.this [int]'分配给它-只读 [英] Property or indexer 'string.this[int]' cannot be assigned to -- it's read only
问题描述
我没有遇到问题-我试图做一个简单的动作:
I didn't get the problem - I was trying to do a simple action:
for(i = x.Length-1, j = 0 ; i >= 0 ; i--, j++)
{
backx[j] = x[i];
}
两个都声明了:
String x;
String backx;
出什么问题了?它说标题中的错误...如果有问题-是否有另一种方法可以解决?结果(正如名称"backx"所暗示的)是backx将向后包含字符串X.P.S.x不为空-它包含另一个字符串的子字符串.
What is the problem ? It says the error in the title... If there is a problem - is there another way to do that? The result (As the name 'backx' hints) is that backx will contain the string X backwards. P.S. x is not empty - it contains a substring from another string.
推荐答案
字符串是不可变的:您可以在某个位置检索字符,但是不能直接将字符更改到新的字符.
Strings are immutable: you can retrieve the character at a certain position, but you cannot change the character to a new one directly.
相反,您必须使用更改来构建新的字符串.有几种方法可以做到这一点,但是 StringBuilder
的工作方式与您已有的方式类似:
Instead you'll have to build a new string with the change. There are several ways to do this, but StringBuilder
does the job in a similar fashion to what you already have:
StringBuilder sb = new StringBuilder(backx);
sb[j] = x[i];
backx = sb.ToString();
如果您查看 string
面向公众的API,则会看到此索引器:
If you take a look at the string
public facing API, you'll see this indexer:
public char this[int index] { get; }
这表明您可以获取"值,但是由于没有设置"可用,因此无法将值分配给该索引器.
This shows that you can "get" a value, but because no "set" is available, you cannot assign values to that indexer.
EDITx2:如果您正在寻找一种反转字符串的方法,则有几种不同的方法,但是这里有一个示例,说明了其工作原理:
EDITx2: If you're looking for a way to reverse a string, there are a few different ways, but here's one example with an explanation as to how it works: http://www.dotnetperls.com/reverse-string
这篇关于无法将属性或索引器'string.this [int]'分配给它-只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!