c# - 如何获取对象的键作为键值对?
问题描述
我有类对象,我需要以特定格式存储它的值和键。
public class AppSettings
{
public int TokenLifeTime { get; set; } = 450;
public List<string> Urls { get; set; } = new List<string>
{
"www.google.com",
"www.hotmail.com"
};
public List<ServersList> ServersList { get; set; } = new List<ServersList>
{
new ServersList {IsHttpsAllowed = false},
new ServersList {IsHttpsAllowed = true}
};
}
public class ServersList
{
public bool IsHttpsAllowed { get; set; }
}
我想获得这种格式的密钥。
"AppSettings:TokenLifeTime" , 450
"AppSettings:Urls:0", "www.google.com"
"AppSettings:Urls:1", "www.hotmail.com"
"AppSettings:ServersList:0:IsHttpsAllowed", false
"AppSettings:ServersList:1:IsHttpsAllowed", true
无论对象深度如何,有什么方法可以递归地将所有键作为字符串。上面的代码只是一个实际情况的例子,我有很长的列表和更多的数据。
解决方案
我不认为有什么开箱即用的。
您需要自己创建一些东西并定义您的规则。
以更原始的形式,我将从以下开始:
Type t = typeof(AppSettings);
Console.WriteLine("The {0} type has the following properties: ",
t.Name);
foreach (var prop in t.GetProperties())
Console.WriteLine(" {0} ({1})", prop.Name,
prop.PropertyType.Name);
IEnumerable
然后为对象和原始值类型添加一个规则以在迭代等中处理它们。
推荐阅读
- javascript - 重命名按钮角9内的函数名称
- angular - 离子角 nbOnInit 未定义?
- java - 在 Java 中使用嵌套 if 语句从数字输入中计算字母等级
- django - Django 查询集获取相关字段名称以过滤聚合总和
- javascript - 为中心传递有效的纬度/经度时,Google Maps 出现 Circle 错误
- reactjs - 如何向这个 React Native Chart 添加渐变颜色?
- jsonschema - JSON Schema 来验证没有时区的 DateTime
- buildozer - 为什么没有创建 buildozer 目录?
- docusignapi - DocuSign 错误:未授权客户端尝试生成访问令牌时
- angular - Recaptcha V2 无法使用 Angular 进行生产