gpt4 book ai didi

c# - 如何将 "sub-classes"放入类(class)

转载 作者:行者123 更新时间:2023-12-02 18:15:35 24 4
gpt4 key购买 nike

我来自 VB,对 C 完全陌生。我有 2 门类(class):

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

关于c# - 如何将 "sub-classes"放入类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22653684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com