C# - 如何确保静态方法直接影响其参数而不仅仅是实例?
C# - How can I insure a static method effects its parameters directly and not just instances?
我有 2 个静态方法,只有一个执行我希望它执行的操作,我无法弄清楚另一个有什么问题。
更具体地说,Method_A 似乎没有创建其参数的实例,而是对在 main 中创建的同一个变量进行操作,而 B 似乎对实例进行操作。
public static Method_A(Vector2[] in, int n)
{
for(int i = 0; i < in.Length; i++)
{
in[i].x = n;
in[i].y = n;
}
}
public static Method_B(Vector2 in, int n)
{
in.x = n;
in.y = n;
}
然后从 main:
// This works, and changes values directly in "test"
Vector2[] test = meshFilter.uv;
Method_A(test, n);
meshFilter.uv = test;
// This FAILS, doesn't affect test
Vector2 test = meshFilter.uv[i];
Method_B(test, n);
meshFilter.uv[i] = test;
// This also FAILS, doesn't affect test
Vector2[] t = meshFilter.uv
(...for loop...){
Vector2 test = t[i];
Method_B(test, n);
t[i] = test;}
meshFilter.uv = t;
我希望方法 B 对原始变量起作用,而不是对某些实例起作用...我该怎么做才能确保这一点?
如果需要更多详细信息,请告诉我。
谢谢。
这就是值类型在 C# 中的工作方式。如果要对原来的struct进行操作,需要传引用。
public static Method_B(ref Vector2 in, int n)
{
in.x = n;
in.y = n;
}
此外,您需要在调用站点指定它已通过引用传递。
Method_B(ref test, n);
您的数组不需要这样做,因为数组是引用类型。它们通过引用 [1] 传递,因此您的 Method_A
正在处理原始数组。
[1] 迂腐地说,数组变量(例如Vector2[] arr
是数组变量)实际上是对数组的引用。 arr
的值默认是按值传递的,由于这是对数组的引用,所以这具有按引用传递数组的效果。
我有 2 个静态方法,只有一个执行我希望它执行的操作,我无法弄清楚另一个有什么问题。 更具体地说,Method_A 似乎没有创建其参数的实例,而是对在 main 中创建的同一个变量进行操作,而 B 似乎对实例进行操作。
public static Method_A(Vector2[] in, int n)
{
for(int i = 0; i < in.Length; i++)
{
in[i].x = n;
in[i].y = n;
}
}
public static Method_B(Vector2 in, int n)
{
in.x = n;
in.y = n;
}
然后从 main:
// This works, and changes values directly in "test"
Vector2[] test = meshFilter.uv;
Method_A(test, n);
meshFilter.uv = test;
// This FAILS, doesn't affect test
Vector2 test = meshFilter.uv[i];
Method_B(test, n);
meshFilter.uv[i] = test;
// This also FAILS, doesn't affect test
Vector2[] t = meshFilter.uv
(...for loop...){
Vector2 test = t[i];
Method_B(test, n);
t[i] = test;}
meshFilter.uv = t;
我希望方法 B 对原始变量起作用,而不是对某些实例起作用...我该怎么做才能确保这一点?
如果需要更多详细信息,请告诉我。
谢谢。
这就是值类型在 C# 中的工作方式。如果要对原来的struct进行操作,需要传引用。
public static Method_B(ref Vector2 in, int n)
{
in.x = n;
in.y = n;
}
此外,您需要在调用站点指定它已通过引用传递。
Method_B(ref test, n);
您的数组不需要这样做,因为数组是引用类型。它们通过引用 [1] 传递,因此您的 Method_A
正在处理原始数组。
[1] 迂腐地说,数组变量(例如Vector2[] arr
是数组变量)实际上是对数组的引用。 arr
的值默认是按值传递的,由于这是对数组的引用,所以这具有按引用传递数组的效果。