2014-03-26 52 views
2

I'm從VB和I'm總新C.未來我有2類:我怎樣才能把「子類」一類

public class Location { 
    public decimal lat {get;set;} 
    public decimal lon {get;set;} 
} 
public class credentials { 
    public string username {get;set;} 
    public string passwordhash {get;set;} 
} 

現在我想用這2類在某些其他類別中,新類似如下:

public class something1 { 
    public string property1 {get;set;} 
    public string property2 {get;set;} 
    // next 2 lines should be avoided -> class "Location" 
    public decimal lat {get;set;} 
    public decimal lon {get;set;} 
    // next 2 lines should be avoided -> class "credentials" 
    public string username {get;set;} 
    public string passwordhash {get;set;} 
} 

我該如何認識到這一點?我不熟悉所有的OO東西。 感謝您的幫助。

回答

6

簡單:

public class something1 { 
    public string property1 {get;set;} 
    public string property2 {get;set;} 
    public Location property3 {get;set;} 
    public credentials property4 {get;set} 
} 

注:

  1. 這是組成的類不是所謂的「子類」他們只是其他類 - 以完全相同的方式string是另一個類。
  2. 我假設你的類在同一個命名空間中,否則你需要在文件中的類定義之上添加一個using MyOtherNamespace

要訪問這些,您可以像訪問something1實例上的任何其他屬性一樣進行操作,例如,

something1 mySomething1 = new Something1(); 
mySomething1.Location = new Location(); 
string cred = mySomething1.credentials.ToString(); // oops you may get a null ref because nothing has been assigned to mySomething1.credentials yet so it will be `null`; 
+0

不要忘記刪除'username'和'passwordhash',太 –

+0

如果我讓這個樣子,訪問LON必須是:something1.Location.lon,對不對?但是我需要一些東西,因爲我得到了序列化的json數據並且想將它存儲在對象中。 –

+0

已更新的答案。 – markmnl