bav*_*aza 13 c# string parsing
我有一个文件包含一个类的一些变量,每一行都是一对:变量,值.我正在寻找一种方法来在运行时加载这些(a-la XmlSerializer),使用反射.
有没有办法在运行时解析string为Type已知的?
以下是一个如意的代码示例,其中最后一行(pi.SetValue()不正确,因为PropertyType是Type没有泛型Parse()方法的类).
using (var sr = new StreamReader(settingsFileName))
{
String line;
while ((line = sr.ReadLine()) != null)
{
String[] configValueStrs = line.Trim().Split(seps);
PropertyInfo pi = configurableProperties
.Single(p => p.Name == configValueStrs[0].Trim());
//How do I manage this?
pi.SetValue(this, pi.PropertyType.Parse(configValueStrs[1].Trim()), null);
}
}
Run Code Online (Sandbox Code Playgroud)
由于所有相关变量都是Ints,Doubles,Strings或Booleans,作为最后的手段,我可以打开类型并使用相应的ToType()方法,但我敢打赌,有一个更优雅的解决方案.
Rus*_*est 24
TypeConverters是要走的路.看看这里有一个很好的例子.
直接来自hanselmans博客:
public static T GetTfromString<T>(string mystring)
{
var foo = TypeDescriptor.GetConverter(typeof(T));
return (T)(foo.ConvertFromInvariantString(mystring));
}
Run Code Online (Sandbox Code Playgroud)
您可以使用静态Convert.ChangeType 方法.它将对象作为其第一个参数和Type要将对象转换为的实例.返回值是您请求的类型,如果没有找到合适的转换,则返回null.此方法抛出4个不同的异常,其中三个异常由它尝试转换的值引起.您可能想要捕获并处理这些.
在您的示例中使用以下函数:
// Convert.ChangeType can throw if the string doesn't convert to any known type
pi.SetValue(this
, Convert.ChangeType(configValueStrs[1], pi.PropertyType)
, null);
Run Code Online (Sandbox Code Playgroud)