c#通过ref传递list元素 [英] c# passing list element by ref

查看:886
本文介绍了c#通过ref传递list元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过ref传递列表元素?



how to pass a list element by ref ?

private void Form1_Load(object sender, EventArgs e)
      {
          List<string> mylist = new List<string>();
          mylist.Add("hi how are you?");
          sara(ref mylist[0]);//there is errore
      }
      public void sara(ref string message)
      {
          message = "hi , i'm fine.";
      }

推荐答案

你不能这样做,因为 ref 期望变量或数组元素。你的 mylist [0] 是一个索引器,所以基本上是一个方法调用。在您的示例中,您只是从方法返回一个值,因此不需要ref参数。但我确信这只是一个例子,你的实际情况更复杂。



这些内容很有趣:

stackoverflow:C#property和ref参数,为什么没有糖? [ ^ ]

stackoverflow:属性或索引器可能不会作为out或ref参数传递 [ ^ ]
You cannot do that, because ref expects variable or array element. Your mylist[0] is an indexer, so basically a method call. In your example you are just returning a value from the method, so there is no need for ref parameter. But I'm sure this is just an example and your real situation is more complicated.

These are interesting to read:
stackoverflow: C# property and ref parameter, why no sugar?[^]
stackoverflow: A property or indexer may not be passed as an out or ref parameter[^]


您已经通过引用正确传递了字符串。请注意,这是一种罕见的情况,通过引用传递引用对象是有意义的,因为System.String是 immutable ,因此您不能通过引用修改同一对象,并且必须创建一个新对象。



但是这个方法,它的签名,仍然没有实用感。此外,您完全忽略输入字符串值。这也没有意义。如果您不需要输入值,请使用 out ,而不是 ref 参数按引用传递。但是你最好写一个字符串函数。如果我通过忽略输入修复问题,该函数可能看起来像

You already correctly passed the string by reference. Note that this is a rare case when passing a reference object by reference makes sense, just because the System.String is immutable, so you cannot modify the same object by its reference and have to create a new one.

But therefore the method, its signature, still has not practical sense. Besides, you completely ignore the input string value. It also makes no sense. If you don't need input value, pass by reference using out, not ref parameter. But then you would better write a string function. If I fix the problem with ignored input, the function could look something like
string Sara(string input) {
    return input + ": I'm fine";
}



不同的签名;方法也可以这样做,但可读性和可用性更好。



-SA


这篇关于c#通过ref传递list元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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