I try to create multiple objects based of one blueprint class and want to fill them with values from an array.
My Blueprint would look as follows:
public class Participant
{
string DateOfBirth;
string Gender;
double BmiValue;
double RelativeFatMass;
double AbsoluteFatMass;
double FatFreeMassValue;
double SkeletalMuscleMassValue;
double SmmTorsoValue;
double SmmRlValue;
double SmmLlValue;
double SmmLaValue;
double SmmRaValue;
double WaistCircumferenceValue;
double WeightValue;
double HeightValue;
double TotalEnergyExpenditureValue;
double RestingEnergyExpenditureValue;
double FfmiValue;
double FmiValue;
double VisceralAdiposeTissueValue;
}
I aim to create objects and fill all those fields with the set values from my array. After on Object is done, I want the same function to create the next object and to repeat this depending on the length of the array.
答案 0 :(得分:0)
您用蓝图描述的内容实际上是一个名为inheritance的概念。我建议你在潜水之前先阅读一下,但这里有一个例子,包括你想要做的事情:
<强> Participant.cs 强>
public class Participant
{
public string firstName { get; set; }
public string secondName { get; set; }
public string gender { get; set; }
public Participant(string firstName, string secondName, string gender)
{
this.firstName = firstName;
this.secondName = secondName;
this.gender = gender;
}
public Participant(string[] args)
{
this.firstName = args[0];
this.secondName = args[1];
this.gender = args[2];
}
}
ParticipantExtended.cs (注意:您可以将其命名为比这更好的东西!)
public class ParticipantExtended : Participant
{
public ParticipantExtended(string firstName, string secondName, string gender) : base(firstName, secondName, gender)
{
this.firstName = firstName;
this.secondName = secondName;
this.gender = gender;
}
public ParticipantExtended(string[] args) : base(args)
{
this.firstName = args[0];
this.secondName = args[1];
this.gender = args[2];
}
}
我们必须再次创建构造函数,因为每个类必须定义自己的构造函数。我放下2个构造函数的原因仅仅是出于示例目的。
SomeFunction()这是您拥有值并想要创建对象的时候
// Supplying parameters to constructor
ParticipantExtended person1 = new ParticipantExtended("John", "Smith", "Male");
// Supplying an array to the constructor
string[] informationAboutPerson = { "Jane", "Jones", "Female" };
ParticipantExtended person2 = new ParticipantExtended(informationAboutPerson);
// Results
string name = person1.firstName; // name = John
string gender = person2.gender; // gender = female
虽然有些不相关,但我建议你看看interfaces,因为在C#中你不能从超过1个类继承。