2012-01-28 34 views
1

我知道這是一個愚蠢的問題,但我一直在自學C#,所以即時學習行話。作爲屬性的方法中,變量的正確名稱是什麼?

我的問題是:當我編寫方法時,當我需要它們共享相同的作用域時,我發現自己在方法的頂部聲明瞭對象和變量。這些類型的對象/變量是否有名字?我知道在一種方法之外宣佈他們將是屬性。

我的意思是示例代碼:我的問題是在Question區域中調用對象的內容。

public Label start_Ping(String target, string name, ref bool router) 
     { 

     #region [ Question ] 
     Label status_Label = new Label(); //Declare the label which will be dynamically  created 

     Ping ping = new System.Net.NetworkInformation.Ping(); //Declare the ping object 

     PingReply reply = null; //Declare the pingReply object  


     byte[] buffer = new byte[100]; //Set the byte size 
     #endregion 

     if (name == "router") 
     { 
      try 
      { 
       reply = ping.Send(target, 50, buffer); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.ToString()); 
      } 
      if (reply.Status == IPStatus.Success) 
      { 
       router = true; 
      } 
      else 
      { 
       router = false; 
       return null; 
      } 
     } 
try 
{ 
... 

在此先感謝。我理解這可能是很簡單=)

回答

0

在你的代碼,status_Labelpingreplybuffer被簡稱爲局部變量

也就是說,他們是本地您創建它們的方法(或您聲明它們的任何範圍)。

沒關係其中在你的方法中,你聲明它們,順便說一句,只要它們在某個範圍內。

+0

感謝您爲我清理。我正在努力添加一些評論,並不知道他們是否有適當的名字。再次感謝! – Botonomous 2012-01-28 16:42:36

+0

另外,如果它們被聲明在方法之外,則稱它們爲** fields **。如果他們有getters和/或setter,他們只被稱爲**屬性**。除非你正在寫這個教C#的人,否則你不應該使用註釋或區域來標記你的本地變量。 – Maggie 2012-01-28 16:47:36

+0

或除非他寫這個指向他的方法身體的具體部分... – BoltClock 2012-01-28 16:51:33

0

BoltClock是正確的,但爲了將來參考,在方法外聲明的變量不是屬性。他們被稱爲成員變量。屬性是不同的。

例如:

public class ExampleClass { 
    String myString = "Hello World!"; 

    public String MyProperty { 
     get { return myString; } 
     set { 
      myString = value; 
      System.Console.WriteLine("MyProperty changed to " + value); 
     } 
    } 
} 

這裏,myString的是一個成員變量(或實例變量)。它不能從課堂外訪問。

顧名思義,MyProperty是一個屬性。它實際上是一種行爲類似變量的方法,但允許其他事情在其值被更改或訪問時發生。在這個例子中,設置MyProperty會輸出一個消息,給出它的新值。

在MSDN herehere上有一些很好的文檔。

希望這會有所幫助。

0

@BoltClock回答了你的問題;然而,我想指出,你的陳述「當變量在方法之外聲明時,它們將是屬性」,這是不正確的。在方法外聲明的變量稱爲字段。屬性通常與字段具有相似的用途(保存值),但它們需要使用getset訪問器進行定義,並且可以合併邏輯,如驗證或屬性更改通知(哪些字段不能)。

例如:

public class Router 
{ 
    private PingReply reply = null; 

    public PingReply Reply 
    { 
     get { return reply; } 
     set { reply = value; } 
    } 
} 

在這種情況下,reply是一個字段,而Reply是獲取或設置的reply的值的屬性。

+0

我一直認爲一個財產是一個財產w /或w/out一個get和set訪問者。感謝您指出了這一點。 – Botonomous 2012-01-28 17:11:48

相關問題