【问题标题】:Add Property in C# using for loop在 C# 中使用 for 循环添加属性
【发布时间】:2021-01-26 14:42:17
【问题描述】:

假设我有学校模型

public class School {

public string Name {get; set;} // property

}

我有一个来自数据库的属性数组列表

var arraylist = ["ComputerParts","CellphoneParts"]

有没有一种方法可以使用 for 循环在学校模型中添加新属性?

这就是我的想法

  1. for 循环数组列表
  2. 在学校模型中添加新属性
//add this -> public string ComputerParts{get; set;} -> in school model
// add this -> public string CellphoneParts {get; set;} -> in school model 

这是预期的结果

public class School {

public string Name {get; set;} 
public string ComputerParts{get; set;}
public string CellphoneParts {get; set;}

}

【问题讨论】:

  • 您是在构建代码生成器还是什么?否则,我看不出这个问题有什么意义。
  • 听起来像是 XY 问题。
  • 您需要告诉我们您想做什么,代码生成器或数据库迁移?
  • 确定有办法 - dynamicreflection + subclass。但这很棘手且难以维护(反射+子类方式)。你应该不惜一切代价避免它!
  • Dictionary<string, string> ExtraColumns { get; } ?

标签: c#


【解决方案1】:

您似乎正在寻找一种方法,通过您的 DTO 在网络上传输一组动态的 键值 对。我建议您使用简单的Dictionary<string, string> 甚至Dictionary<string, object>

public class SchoolDTO {
    public string Name { get; set; } 
    public Dictionary<string, string> ExtraColumns { get; set; }
        = new Dictionary<string, string>();
}

var schoolDTO = new SchoolDTO
{
    Name = "Sample school",
    ExtraColumns =
    {
        { "ComputerParts", "part1,part2,part3" },
        { "CellphoneParts", "part1,part2,part3" }
    }
};

【讨论】:

    猜你喜欢
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多