簡體   English   中英

如何將“子類”放在一個類中

[英]How can I put “sub-classes” in a class

我來自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;}
}

現在,我想以某種方式在其他一些類中使用這兩個類,新類如下所示:

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

我怎么能意識到這一點? 我不熟悉所有的面向對象的東西。 感謝幫助。

簡單:

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`;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM