作为函数参数的字符串变量如何变为只读? [英] How a string variable as a parameter of a function becomes readonly?

查看:166
本文介绍了作为函数参数的字符串变量如何变为只读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,获取错误为

属性或索引器'  string。此[int]'无法分配给 -   只读





为什么在没有用户将其设置为只读的情况下设置为readonly?



  private  void  function  string  text)
{
int index = 0;
text [ 0 ] = ' a' ;

while (index< text.Length)
{
Console.WriteLine(< span class =code-string> 字符串的字符是 + text [index]);
index ++;
}
}



 

解决方案

Item String 类的索引属性本质上是只读的,即它只用一个属性getter定义,没有属性setter。

这不是用户可以选择的。



你可能需要一个 StringBuilder 代替:

 StringBuilder sb =  new  StringBuilder(text); 
sb [ 0 ] = ' a' ;





希望这会有所帮助。


因为字符串是不可变的 C#,请参阅 字符串(C#参考) [ ^ ]。

In the below code, getting an error as

Property or indexer 'string.this[int]' cannot be assigned to -- it is read only



Why it is set readonly without user set it as readonly?

private void function(string text)
        { 
            int index = 0;
            text[0] = 'a';

            while(index < text.Length)
            {
                Console.WriteLine("The characters of string are" + text[index]);
                index++;
            }
        }


解决方案

The Item indexed property of String class is readonly by nature, i.e. it is defined with only one property getter and no property setter.
This is not something to be chosen by user.

You may need a StringBuilder instead:

StringBuilder sb = new StringBuilder(text);
sb[0] = 'a';



Hope this helps.


Because strings are immutable in C#, see, for instance "string (C# Reference)"[^].


这篇关于作为函数参数的字符串变量如何变为只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆