2014-03-26 117 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