Tre*_*ree 7 c# arrays reference
我怎么能这样做?
int v1 = 4;
int v2 = 3;
int v3 = 2;
int v4 = 1;
int [] vars = new int [] {ref v1, ref v2, ref v3, ref v4};
for (var i = 0; i < 4; i++) {
ChangeVar (vars [i], i);
}
void ChangeVar (ref int thatVar, int newValue) {
thatVar = newValue;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我想这样做是因为这些变量是由其他类直接访问的.例如v1可以是某物的宽度,v2可以是某物的高度.我的一些类使用width变量来限制它必须从用户获得的输入的长度.有些类使用height变量来做其他事情.但我希望能够使用循环编辑这些变量,因为现在这是编辑过程的工作方式:
int indexOfVarToChange = GetIndex ();
switch (indexOfVarToChange) {
case 0:
int newValue = GetNewValue ();
width = newValue;
break;
case 1:
int newValue = GetNewValue ();
height = newValue;
break;
}
Run Code Online (Sandbox Code Playgroud)
我必须手动重新分配变量,因为我不能在循环中使用这些变量的引用数组.我有超过30个独特的变量,我必须这样做,这是一个痛苦.
我想回退计划是将所有这些变量移动到一个字典中,并拥有一个包含所有键的数组,并将每个键传递给编辑函数.
你不能。
您仍然可以就地编辑元素,但只能直接分配给它们:
vars[2] += 42;
Run Code Online (Sandbox Code Playgroud)
但是我刚刚测试了这个作品:
using System;
public class Test
{
private static void assign(ref int i)
{
i = 42;
}
public static void Main()
{
var vars = new [] { 1,2,3,4 };
Console.WriteLine(vars[2]);
assign(ref vars[2]);
Console.WriteLine(vars[2]);
}
}
Run Code Online (Sandbox Code Playgroud)
输出量
3
42
Run Code Online (Sandbox Code Playgroud)
作为一项心理锻炼,我想出了这种生病缠结的机制来仍然得到您想要的东西(但要花更多的钱而不是简单地将所有整数装箱):
private class Wrap<T> where T : struct
{
public T Value;
public static implicit operator Wrap<T>(T v) { return new Wrap<T> { Value = v }; }
public static implicit operator T(Wrap<T> w) { return w.Value; }
public override string ToString() { return Value.ToString(); }
public override int GetHashCode() { return Value.GetHashCode(); }
// TODO other delegating operators/overloads
}
Run Code Online (Sandbox Code Playgroud)
现在,a Wrap<int>将大致表现为常规int(在比较,相等和运算符领域需要更多的工作)。您可以使用它来编写此代码,并使它按您想要的方式工作:
private static void assign(ref int i)
{
i = 42;
}
public static void Main()
{
Wrap<int> element = 7;
var vars = new Wrap<int>[] {1, 2, element, 3, 4};
Console.WriteLine(vars[2]);
assign(ref vars[2].Value);
Console.WriteLine(element);
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)
输出:
7
42
Run Code Online (Sandbox Code Playgroud)