Variables 当C中存在同名的局部变量时,如何更改函数中全局变量的值#

Variables 当C中存在同名的局部变量时,如何更改函数中全局变量的值#,variables,c#-4.0,global-variables,local,Variables,C# 4.0,Global Variables,Local,我想更改函数中的全局变量,其中已经存在相同的局部变量 int x=10; //global variable void fun1() { fun2(5); } void fun2(int x) { x=7; //here i want that this statement assigns the value 7 to the global x } this.x用于非静态类 NameClass.x用于静态变量重命名本地参数值。 int x=10; //global

我想更改函数中的全局变量,其中已经存在相同的局部变量

int x=10;     //global variable
void fun1()
{
fun2(5);
}

void fun2(int x)
{
x=7;       //here i want that this statement assigns the value 7 to the global x
}

this.x
用于非静态类


NameClass.x
用于静态变量

重命名本地参数值。
int x=10;     //global variable
void fun1()
{
fun2(5);
}

void fun2(int lx)
{
x=7;  //if you want 7
x=lx;  //if you want the paramValue
}
就像尤里·维库洛夫说的。
this.x
用于非静态变量

int x=10;     //global variable
void fun1()
{
fun2(5);
}

void fun2(int lx)
{
x=7;  //if you want 7
x=lx;  //if you want the paramValue
}

只要用
这个
来限定它就行了。这是一种非常常见的模式,特别是对于构造函数:

public class Player
{
    private readonly string name;

    public Player(string name)
    {
        this.name = name;
    }
}

虽然我认为如果您的参数真的是字段的新值(例如,在一个基于当前实例和单个字段的新值创建新实例的方法中)可以接受,但从可读性的角度来看,我通常会尽量避免使用它。当然,私有字段的名称是一个实现细节,但是在阅读方法的代码时,用同一个变量名表示两个不同的概念是令人困惑的。

有没有其他方法不更改名称和参数值?是的。使用'this.x'表示globalvariable,使用'x'表示localBy“global variable”您真正的意思是“instance variable”-它不是全局的,因为它特定于一个实例。