【问题标题】:How to return method value to it's origin in C#如何在 C# 中将方法值返回到它的原点
【发布时间】:2014-04-03 18:14:11
【问题描述】:

在这个例子中,我有 3 个值被一个类中的方法使用。

主要方法:

String testString;
List<String> testList = new List<String>(){
   "Value1",
   "Value2",
   "Value3",
}
int goGet = 2;

TestClass.DrawString(testString, testList, goGet);

班级:

class TestClass
{
    public static void DrawString (String myString, List<String> myList, int get){
       myString = myList.ElementAt(get);
       get = get + 1;        
    }
}

我想知道我是否可以将值返回到它们在类中的原始位置(即 myString 到 testString、myList 到 testList 和 get 到 goGet),如果可以的话,如何。

【问题讨论】:

  • 你为什么传入“myString”而不是让DrawString的返回类型是字符串?

标签: c# methods return


【解决方案1】:

你想看看使用ref (C# Reference)关键字

ref 关键字导致参数通过引用传递,而不是通过 价值。通过引用传递的效果是对 方法中的参数反映在基础参数中 调用方法中的变量。参考参数的值为 始终与基础参数变量的值相同。

要使用 ref 参数,方法定义和调用 方法必须显式使用 ref 关键字

必须初始化传递给 ref 参数的参数 在通过之前。这与 out 参数不同,其参数 在传递之前不必显式初始化。

所以把方法签名改成

public static void DrawString (ref String myString, List<String> myList, ref int get)

和调用语句到

TestClass.DrawString(ref testString, testList, ref goGet);

【讨论】:

  • 值得注意的是int和List之间的区别是一个是原始的,另一个是一个对象。
猜你喜欢
  • 2021-11-28
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
相关资源
最近更新 更多