如何在课堂上放置"子课程"

Oli*_*pel 2 c#

我来自VB,我是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;}
}
Run Code Online (Sandbox Code Playgroud)

现在我想以某种方式在其他一些类中使用这两个类,新类看起来像这样:

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;}
}
Run Code Online (Sandbox Code Playgroud)

我怎么能意识到这一点?我不熟悉所有OO的东西.感谢帮助.

mar*_*mnl 6

简单:

public class something1 {
  public string property1 {get;set;}
  public string property2 {get;set;}
  public Location property3  {get;set;}
  public credentials property4 {get;set}
}
Run Code Online (Sandbox Code Playgroud)

注意:

  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`;
Run Code Online (Sandbox Code Playgroud)