0

我如何明确地引用参数而不是成员变量?

static recursive{

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

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

7 回答 7

2

非限定引用将始终引用参数,因为它位于更本地的范围内。

如果要引用成员变量,则需要使用类的名称来限定它(或者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 编码风格指南都强烈建议使用属性而不是公开公共字段。而且由于这些总是驼峰式的,所以这个问题自己解决了。

于 2011-06-15T14:55:00.190 回答
0
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
    }
}
于 2011-06-15T14:55:08.410 回答
0
public static void Recursive(List<string> output){
        ...
    }

引用的块中的代码output将始终是本地的而不是成员变量。

如果你想引用成员变量,你可以使用recursive.output.

于 2011-06-15T14:55:15.210 回答
0

当你在Recursive静态方法里面时output会指向该方法的参数。如果要指向静态字段,请使用静态类的名称作为前缀:recursive.output

于 2011-06-15T14:55:20.563 回答
0

给你的成员变量另一个名字。惯例是在公共静态成员上使用 Camelcasing。

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

public static void Recursive( List<string> output )
{
   Output = output;
}
于 2011-06-15T14:55:24.597 回答
0

您可以显式引用recursive.output以指示静态成员,但重命名参数或成员会更清晰。

于 2011-06-15T14:56:04.853 回答
0

我知道没有办法明确地引用一个参数。通常处理这种情况的方法是给成员变量一个特殊的前缀,例如_m_这样参数将永远不会具有完全相同的名称。另一种方法是使用 this.var 引用成员变量。

于 2011-06-15T14:56:11.383 回答