C# 如何在c中向其他对象添加对象#
我自己在做学校学位课程。 但我想把度对象添加到程序对象中,这是一个比度更广泛的概念,以便执行一行来实现这个程序。 (我对这个项目有进一步的了解,但我想知道的一个基本概念是这个问题) 例如,我像下面这样编码C# 如何在c中向其他对象添加对象#,c#,C#,我自己在做学校学位课程。 但我想把度对象添加到程序对象中,这是一个比度更广泛的概念,以便执行一行来实现这个程序。 (我对这个项目有进一步的了解,但我想知道的一个基本概念是这个问题) 例如,我像下面这样编码 namespace Mod1_SelfAssesment { public class UniProgram { public string Programme { get; set; } public UniProgram(string pr
namespace Mod1_SelfAssesment
{
public class UniProgram
{
public string Programme { get; set; }
public UniProgram(string programme)
{
this.Programme = programme;
}
Degree master = new Degree("Master");
}
}
namespace Mod1_SelfAssesment
{
public class Degree
{
public string _Degree { get; set; }
public Degree(string degree)
{
this._Degree = degree;
}
}
}
这样,我必须在Main方法中实例化两个类,这不是我想要执行的。UniProgram类中的“代码学位硕士=新学位(“硕士”);”在这里没有任何用法
你能帮我一下吗
提前谢谢你~ 如果我没弄错
namespace Mod1_SelfAssesment
{
public class UniProgram
{
public string Programme { get; set; }
public IList<Degree> Degrees {get;set;}
public UniProgram(string programme)
{
this.Programme = programme;
Degrees = new List<Degree>();
}
namespace Mod1_SelfAssesment
{
public class Degree
{
public string _Degree { get; set; }
public Degree(string degree)
{
this._Degree = degree;
}
}
}
namespace Mod1\u自评估
{
公共课程
{
公共字符串程序{get;set;}
公共IList度{get;set;}
公共计划(字符串计划)
{
本方案=方案;
度=新列表();
}
名称空间Mod1_自评估
{
公立学位
{
公共字符串_度{get;set;}
公共学位(字符串学位)
{
这个。_度=度;
}
}
}
似乎您希望将度
作为UniProgram
的一个属性。如果是这样,您可以添加一个额外的构造函数(链接它们),以便在一行中定义两者
public class UniProgram
{
public string Programme { get; set; }
public Degree Degree { get; set; }
public UniProgram(string programme)
{
this.Programme = programme;
}
// Second constructor so you can also define degree
// : this(...) allows you to call other constructor so either can be used
public UniProgram(string programme, string degree) : this (programme)
{
this.Degree = new Degree(degree);
}
}
现在,您可以通过两种方式使用该程序
// Usage example
var program = new UniProgram("Program without degree");
var programWithDegree = new UniProgram("Program with degree", "Master");
根据注释,如果你的程序允许多个学位,你可以考虑其他答案。这是另一种方式。
public class UniProgram
{
public string Programme { get; set; }
public IList<Degree> Degrees { get; } = new List<Degree>();
public UniProgram(string programme, params string[] degree)
{
this.Programme = programme;
foreach (var name in degree)
this.Degrees.Add(new Degree(name));
}
}
要了解有关上述代码/上述功能的更多信息,请执行以下操作:
- 参数数组:
- 收藏/列表:
- 特性:
- 建造商:
列表master
来存储多个硕士学位。谢谢你。我认为你的方法是正确的。顺便问一下,第二个构造函数旁边的“:this(program)”角色是什么?这是否表示第一个构造函数的参数?如果我不使用“:这个…”啊~~我自己能理解。非常感谢~!
// Additional usage scenarios
var programMultiple = new UniProgram("Multiple degrees", "Master", "Doctorate");
programMultiple.Degrees.Add("Another degree"); // You can also add degrees any time later