明确引用参数

问题描述

| 如何显式引用参数而不是成员变量?
static recursive{

    public static List<string> output = new List<string>();

    public static void Recursive(List<string> output){
        ...
    }
}
    

解决方法

        不合格的引用将始终引用该参数,因为它位于更局部的范围内。 如果要引用成员变量,则需要使用类名对其进行限定(对于非静态成员变量,则为
this
)。
output = foo;              // refers to the parameter
recursive.output = foo;    // refers to a static member variable
this.output = foo;         // refers to a non-static member variable
但是您可能仍然应该更改名称。它使您的代码更易于阅读。 而且您根本不应该具有公共静态变量。所有.NET编码样式指南都强烈建议使用属性,而不是公开公共字段。而且由于它们总是被骆驼装箱,这个问题可以解决。     ,        
public static void Recursive(List<string> output){
        ...
    }
块中引用“ 4”的代码将始终是本地的,而不是成员变量。 如果要引用成员变量,可以使用
recursive.output
。     ,        当您在
Recursive
静态方法中时,
output
将指向该方法的参数。如果要指向静态字段,请使用静态类的名称作为前缀:
recursive.output
    ,        给您的成员变量起另一个名字。 约定是在公共静态成员上使用驼峰式。
public static List<string> Output = new List<string>();

public static void Recursive( List<string> output )
{
   Output = output;
}
    ,        您可以显式引用“ 5”来指示静态成员,但是重命名参数或成员会更干净。     ,        我不知道显式引用参数的方法。通常的处理方式是为成员变量赋予特殊的前缀,例如
_
m_
,以使参数永远不会具有完全相同的名称。另一种方法是使用this.var引用成员变量。     ,        
public class MyClass {
    public int number = 15;

    public void DoSomething(int number) {
        Console.WriteLine(this.number); // prints value of \"MyClass.number\"
        Console.WriteLine(number); // prints value of \"number\" parameter
    }
}
编辑:: 对于静态字段,必须使用类名而不是\“ this \”:
public class MyClass {
    public static int number = 15;

    public void DoSomething(int number) {
        Console.WriteLine(this.number); // prints value of \"MyClass.number\"
        Console.WriteLine(MyClass.number); // prints value of \"number\" parameter
    }
}