2011-06-15 30 views
0

如何顯式引用參數而不是成員變量?顯式引用參數

static recursive{ 

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

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

我認爲這將在遞歸函數作用域中不明確。僅僅因爲你可以做一些事情並不意味着你應該 - 使用不同的變量名稱來改變參數 – 2011-06-15 14:54:21

+0

的名字,否則這將會非常混亂。 – BrokenGlass 2011-06-15 14:56:43

+0

我同意這是模糊的,但是,這只是一個例子來說明我在找什麼。 – Andrew 2011-06-15 14:56:57

回答

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編碼風格準則強烈建議屬性而不是暴露公共字段。而且由於這些都是駱駝式的,所以這個問題就解決了。

+0

在這種情況下,這是不可能的,因爲它是靜態的。 – 2011-06-15 14:55:42

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 
    } 
} 

編輯:

對於靜態字段是必需的,而不是 「這」 類的名稱:

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 
    } 
} 
+0

topicstarter處於靜態上下文中,因此靜態是不可能的。 – 2011-06-15 14:56:37

+0

@Frederik Gheysels:你錯了。有辦法 - 看看我的編輯部分。 – TcKs 2011-06-15 18:51:12

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

在塊中的代碼是指output將始終是本地&不是成員變量。

如果你想引用成員變量,你可以使用recursive.output

0

當您在Recursive裏面時,靜態方法output將指向該方法的參數。如果要指向靜態字段,請使用靜態類的名稱作爲前綴:recursive.output

0

爲您的成員變量指定另一個名稱。 約定是在公共靜態成員上使用Camelcasing。

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

public static void Recursive(List<string> output) 
{ 
    Output = output; 
} 
+2

這不是camelCasing,那是PascalCasing。 – 2011-06-15 14:59:21

0

你可以明確地引用recursive.output指示靜態成員,但它是清潔劑或者重命名的參數或成員。

0

我知道沒有辦法明確引用參數。通常處理的方式是給成員變量一個特殊的前綴,如_m_,這樣參數永遠不會有完全相同的名稱。另一種方法是使用this.var引用成員變量。