如何在 C# 中将方法值返回到其原点



在这个例子中,我有 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 to goGet),如果是的话

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

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

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

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

因此,将方法签名更改为

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

和调用语句

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

最新更新