我有一个类对象,我需要以特定的格式存储它的值和键。
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有没有办法以递归的方式获得所有的键作为字符串,而不管对象的深度。上面的代码只是一个例子,在真实情况下,我有很长的列表和更多的数据。
发布于 2020-02-11 15:03:34
我不认为有任何开箱即用的东西。
你需要自己创建一些东西并定义你的规则。
在其更原始的形式中,我将从以下内容开始:
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在对象和原始值类型的迭代中处理它们,依此类推。
发布于 2020-02-11 13:54:53
我给你举几个例子:
选项1:
public class AppSettings
{
public int TokenLifeTime { get; set; } = 450;
public Dictionary<string, ServersList> Urls { get; set; } = new Dictionary<string, ServersList>
{
{"www.google.com", new ServersList {IsHttpsAllowed = false}},
{ "www.hotmail.com", new ServersList {IsHttpsAllowed = true}}
};
}
public class ServersList
{
public bool IsHttpsAllowed { get; set; }
}此选项将把这些值组合在一起,但您将丢失基于'int‘的索引。不确定这是否重要。
选项2:
public class AppSettings
{
public int TokenLifeTime { get; set; } = 450;
public List<KeyValuePair<string, ServersList>> Urls { get; set; } = new List<KeyValuePair<string, ServersList>>
{
new KeyValuePair<string, ServersList>("www.google.com",new ServersList {IsHttpsAllowed = false}),
new KeyValuePair<string, ServersList>("www.hotmail.com", new ServersList {IsHttpsAllowed = true})
};
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; }
}此选项将保留基于“int”的索引,并且仍对值进行分组。但感觉很笨拙..。
选项3:(我会选择的那个)
public class AppSettings
{
public int TokenLifeTime { get; set; } = 450;
public List<Server> ServersList { get; set; } = new List<Server>
{
new Server { Url = "www.google.com", IsHttpsAllowed = false},
new Server { Url = "www.hotmail.com", IsHttpsAllowed = true}
};
}
public class Server
{
public string Url { get; set; }
public bool IsHttpsAllowed { get; set; }
}这个选项仍然提供基于“int”的索引,它将数据分组在一起(正如我在示例中所理解的那样)。
https://stackoverflow.com/questions/60162468
复制相似问题