解析从参数中取出的字符串的最佳方法是什么?
我目前正在使用以下函数解析XML节点,但希望将其设为通用。
private void ParseSettings(XmlDocument doc)
{
IsFormVisible = (bool) ParseNode(doc, "Settings/IsFormVisible", IsFormVisible);
UpdaterRunInterval = (int) ParseNode(doc, "Settings/UpdaterRunInterval", UpdaterRunInterval);
UpdaterLastRunTime = (DateTime) ParseNode(doc, "Settings/UpdaterLastRunTime", UpdaterLastRunTime);
}
private object ParseNode(XmlDocument doc, string node, object defaultValue)
{
try
{
XmlNode xmlNode = doc.SelectSingleNode(node);
if (xmlNode == null)
return defaultValue;
string text = xmlNode.InnerText;
if (defaultValue is int)
return int.Parse(text);
if (defaultValue is bool)
return bool.Parse(text);
if (defaultValue is string)
return text;
if (defaultValue is DateTime)
return DateTime.Parse(text);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return defaultValue;
}
答案 0 :(得分:2)
private T ParseNode<T>(XmlDocument doc, string node, T defaultValue)
{
try
{
XmlNode xmlNode = doc.SelectSingleNode(node);
if (xmlNode == null)
return defaultValue;
string text = xmlNode.InnerText;
return SafeConvert(text, defaultValue);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return defaultValue;
}
public static T SafeConvert<T>(string s, T defaultValue)
{
if ( string.IsNullOrEmpty(s) )
return defaultValue;
return (T)Convert.ChangeType(s, typeof(T));
}
答案 1 :(得分:1)
尝试类似:
private static T ParseNode<T>(XmlDocument doc, string node, object defaultValue)
{
object ret = defaultValue;
try
{
XmlNode xmlNode = doc.SelectSingleNode(node);
if (xmlNode == null)
return default(T);
string text = xmlNode.InnerText;
if (defaultValue is int)
ret = int.Parse(text);
if (defaultValue is bool)
ret = bool.Parse(text);
if (defaultValue is string)
ret = text;
if (defaultValue is DateTime)
ret = DateTime.Parse(text);
return (T) ret;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return (T)ret;
}
我无法保证,这是完美的做法,但它有效!
IsFormVisible = ParseNode<bool>(doc, "Settings/IsFormVisible", true);
UpdaterRunInterval = ParseNode<int>(doc, "Settings/UpdaterRunInterval", 1);
UpdaterLastRunTime = ParseNode<DateTime>(doc, "Settings/UpdaterLastRunTime", 1);