C# - 将数据添加到对象内部的对象

标签 c# .net list

我有以下类(class)

public class manoeuvresID
{
    public string manName { get; set; }
    public int manID { get; set; }
}

public class testID
{
    public string testName { get; set; }
    public int ID { get; set; }
    public IList<manoeuvresID> manoeuvres { get; set; }
}

并希望将数据添加到类型为 testID 的新列表中

        HardCodedDatabase.testID testObjet = new HardCodedDatabase.testID();
        testObjet.testName = "test1";
        testObjet.manoeuvres = "man1";

        List<HardCodedDatabase.testID> listForTesting = new List<HardCodedDatabase.testID>();
        listForTesting.Add(testObjet);

问题是我不知道如何给 testobjet.manoeuvres 添加值

最佳答案

初始化列表(最好通过构造函数)然后添加一个对象:

testObjet.Manoeuvres = new List<ManoeuvresId>();
ManoeuvresId id = new ManoeuvresId();
id.ManId = 1;
id.ManName = "man1";
testObjet.Manoeuvres.Add(id);

这是一个可能的构造函数实现(也修复了命名问题)。

public class TestId
{
    public TestId() : this(-1, null) { }
    public TestId(int id) : this(id, null) { }
    public TestId(string name) : this(-1, name) { }
    public TestId(int id, string name)
    {
        this.ID = id;
        this.TestName = name;
        this.Manoeuvres = new List<ManoeuvresId>();
    }

    public string TestName { get; set; }
    public int ID { get; set; }
    public IList<ManoeuvresId> Manoeuvres { get; set; }
}

然后确保列表始终被初始化,您可以将其简化为:

TestId testObjet = new TestId(1, "test1");
testObjet.Manoeuvres.Add(new ManoeuvresId { ManId = 1, ManName = "man1" });

关于C# - 将数据添加到对象内部的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37409495/

相关文章:

.net - 了解为 Umbraco 添加/创建新模板的基础知识

c# - 寻找循环列表解决方案

c# - 如何在 C# 中将 X 列表转换为 Y 列表?

list - 如何将 java.util.List 转换为 Scala 列表

java - Vaadin 随机播放 ListSelect

c# - 如何在Windows窗体下使用Quartz .net?

c# - 显示paypal信息

c# - 如何在片段中转义字符串插值

c# - 最小起订量 : Property is correctly set as virtual but still have invalid setup on a non-virtual member

.net - 巡航控制.NET : using cb:define with multiple parameters