如何创建包含n个字符串属性和一个数据对象但具有其属性的对象类型可以在C#中动态更改的对象列表

时间:2019-06-16 05:28:42

标签: c# design-patterns

我要根据对象类型动态加载属性“ Data”。我不想做这样的事情:

        List<BaseBoxDTO> listBoxes = new List<BaseBoxDTO>();
        BaseBoxDTO box = new BaseBoxDTO();
        box.Title = "Title1";
        box.Status = "Status1";
        GeneralInfoBoxDTO GI = new GeneralInfoBoxDTO
        {
            value1 = "string1",
            value2 = "string2"
        };
        box.Data = GI;
        listBoxes.Add(box);

        BaseBoxDTO box2 = new BaseBoxDTO();
        box2.Title = "Title2";
        box2.Status = "Status2";

        TrainingBoxDTO traini = new TrainingBoxDTO
        {
            valorproperty1 = "string1",
            valorproperty2 = "string2"
        };
        box2.Data = traini;
        listBoxes.Add(box2);

List<BaseBoxDTO> listBoxes = new List<BaseBoxDTO>(); BaseBoxDTO box = new BaseBoxDTO(); box.Title = "Title1"; box.Status = "Status1"; GeneralInfoBoxDTO GI = new GeneralInfoBoxDTO { value1 = "string1", value2 = "string2" }; box.Data = GI; listBoxes.Add(box); BaseBoxDTO box2 = new BaseBoxDTO(); box2.Title = "Title2"; box2.Status = "Status2"; TrainingBoxDTO traini = new TrainingBoxDTO { valorproperty1 = "string1", valorproperty2 = "string2" }; box2.Data = traini; listBoxes.Add(box2); 我认为应该有一种更好的方法,也许使用递归方法。我有以下结构

public class BaseBox
    {
        public string Title { get; set; }
        public string Status { get; set; }
        public object Data { get; set; }
    }

 public class ChildBox: BaseBox
    {
        public string value1 { get; set; }
        public string value2 { get; set; }
    }

 public class ChildBox2: BaseBox
    {
        public string valueproperty { get; set; }
        public string valueproperty2 { get; set; }

    }

0 个答案:

没有答案