如何将样式文本转换为 C# 对象,例如类/哈希表/集合

本文关键字:集合 对象 哈希表 样式 文本 转换 | 更新日期: 2023-09-27 17:56:31

我有这样的样式文本:

".abc {border: 1px solid blue;color:black;...} 
.abc{background-image:url('http://example.com/images/a.png')...}
#abcd {color: blue}..."

我需要在服务器中编辑此文本(更改背景图像或添加颜色属性...),然后将其另存为文本。

我认为最好的方法是将此文本转换为 c# 对象,例如类/哈希表/集合......

有人可以帮助我解决这个问题吗?

谢谢。

如何将样式文本转换为 C# 对象,例如类/哈希表/集合

我的建议是在 C# 代码中保留尽可能少的样式信息。 最好在CSS文件中定义对应于不同样式的不同类,然后仅处理服务器端的类名。

使用CssStyleCollection内置类。

System.Web.UI.WebControls.Style style = new System.Web.UI.WebControls.Style(); 
// you can set various properties on style object.
CssStyleCollection cssStyleCollection = style.GetStyleAttributes(SOME_USER_CONTROL OR YOUR PAGE);
cssStyleCollection.Add("border", "1px solid blue"); // etc

另一种选择是使用以下结构:

List<KeyValuePair<string, List<KeyValuePair<string, string>>> cssValues = new List<KeyValuePair<string, List<KeyValuePair<string, string>>>();
cssValues.Add(new KeyValuePair<string, List<KeyValuePair<string, string>>("abc", new List<KeyValuePair<string, string>>
{
 new KeyValuePair<string, string>("border", "1px solid blue"),
 new KeyValuePair<string, string>("color", "black"),
 // so on
}));

我们使用 KeyValuePair 列表而不是字典,因为 CSS 类可以重复并且不能保证唯一性。