[英]Add Property in C# using for loop
假設我有學校模型
public class School {
public string Name {get; set;} // property
}
我有一個來自數據庫的屬性數組列表
var arraylist = ["ComputerParts","CellphoneParts"]
有沒有辦法可以使用 for 循環在學校模型中添加新屬性?
這就是我的想法
//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;}
}
看起來您正在尋找一種使用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" }
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.