我有一个大的 .ini 文件。欧共体:
[Globals]
EdgeDkShadowColor = 188 196 218
EdgeFillColor = 244 244 244
[SysMetrics]
ActiveCaption = 207 214 232
Background = 58 110 165
Btnface = 244 244 244
...
[Button.Checkbox]
AccentColorHint = 250 196 88
Bgtype = imagefile
BorderColorHint = 29 82 129
FillColorHint = 33 161 33
...
[Button.Checkbox(Checkeddisabled)]
TextColor = 161 161 146
[Button.Checkbox(Mixeddisabled)]
TextColor = 161 161 146
[Button.Checkbox(Uncheckeddisabled)]
TextColor = 161 161 146
我创建了静态类。我想枚举 .ini 的行并为类参数中的所有字段设置值。
类结构是:
public static class Parameters
{
public static class Globals
{
public static string EdgeDkShadowColor;
public static string EdgeFillColor;
...
}
public static class SysMetrics
{
public static string ActiveCaption;
public static string Background;
public static string Btnface;
...
}
public static class Button
{
public static class Checkbox
{
public static string AccentColorHint;
public static string Bgtype;
public static string BorderColorHint;
}
public static class Checkbox_Checkeddisabled
{
public static string TextColor;
}
public static class Checkbox_Mixeddisabled
{
public static string TextColor;
}
public static class Checkbox_Uncheckeddisabled
{
public static string TextColor;
}
...
如何正确枚举类中的所有字段并初始化它们以最终获得一个对象:
Parameters.
Globals.
EdgeDkShadowColor = "188 196 218";
EdgeFillColor = "244 244 244";
SysMetrics.
ActiveCaption = "207 214 232"
Background = "58 110 165"
Btnface = "244 244 244"
...
Button.
Checkbox.
AccentColorHint = "250 196 88"
Bgtype = "imagefile"
BorderColorHint = "29 82 129"
... etc.
附言
- 所有值都是字符串。
- '(' 中的名称替换为 '_'。
- 参数名称可以包含字符串“::”。它被“分机”取代。
更新
我找到了这个任务的第一个代码。我尝试使用此功能:代码的主要部分是
StringReader str = new StringReader(fileAsString);
string line;
Type curType = null;
while ((line = str.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line) | line.StartsWith(";")) continue;
if (line.Contains('['))
{
line = line[0] + line[1].ToString().ToUpper() + line.Substring(2);
var listing = typeof(Parameters).GetNestedTypes().ToList();
string lineS = line.Trim('[').Trim(']').Trim(')').
Replace("(", "_").Replace("::", "Ext").Trim();
var listingOf = listing.Find(tipe => tipe.Name == lineS);
curType = listingOf;
}
else
{
if (curType != null)
{
FieldInfo found = curType.GetField(splits[0].Trim(')').Replace("(", "_").Trim());
if (found != null)
found.SetValue(null, splits[1].Trim());
}
}
}
这是工作,但仅限于一个级别。这是此代码的工作结果: