我有这样的与值的文件:访问变量,编写一个基于领域的文本文件值变量
[Params]
Version=106
Monitor=0
SMode=10000000
Date=20120519
在我组装我的属性对应于这些领域,如此:
public static string Version { get; set; }
public static string Monitor { get; set; }
public static string SMode { get; set; }
public static DateTime Date { get; set; }
我通过这样的文件进行迭代(_params与从[PARAMS]部分中的文件中的行的字符串列表):
foreach (string s in _params)
{
string[] values = s.Split('=');
}
如何找到值为[0]的变量并将其设置为值[1]?
编辑:
感谢阿提拉,这结束了我的解决方案。我通过文件中的文本找到属性字段,并从文件中设置值。我也根据属性的数据类型设置正确的类型。我必须做一些字符串的一些转换,使它们转换为datetime数据类型:
foreach (string s in _params)
{
string[] values = s.Split('=');
object myObject = values[0];
object myValue = values[1];
if (myObject.ToString() == "Date")
myValue = ConvertDateStringToDateTime(values[1]);
if (myObject.ToString() == "StartTime")
myValue = ConvertStartTimeStringToDateTime(values[1]);
if (myObject.ToString() == "Length")
myValue = ConvertLengthStringToTimeSpan(values[1]);
var type = typeof(HrmParams);
var field = type.GetProperty(myObject.ToString());
myValue = Convert.ChangeType(myValue, field.PropertyType);
field.SetValue(myObject, myValue, null);
}
你必须使用反射。 –