问题描述
|
我正在解析大量的xml内容,并填充一个DTO以提交给合作伙伴端点。 xml内容存储在我定期读取并发送的文本文件中。无论如何,我现在发现自己喜欢Funcs,就像这样:
Func<string,int> ConvertInt= (p) => String.IsNullOrEmpty(p) ? 0 : Convert.ToInt32(p);
我检查我正在读取的元素是否不包含值,并且是否不发送默认值,即在整数情况下为0。我对于double和DateTime?有相似的值是无论如何有转换它,所以我可以说一个扩展方法可以处理所有类型,即int,double和DateTimes?同样,我执行此转换的原因是,让我们说DTO期望但不是必需的某个整数值,我不想尝试将空字符串强制转换为它,依此类推。 。如果没有Date值,我只想返回一个空值,因为DTO接受可为空的日期时间,因此我编写了函数,并希望进行合并。
解决方法
您应该看看TypeConverter类:http://msdn.microsoft.com/zh-cn/library/system.componentmodel.typeconverter.aspx
protected X Convert<X>(string value)
{
X val = default(X);
var tc = TypeDescriptor.GetConverter(typeof(X));
if (!string.IsNullOrEmpty(value) && tc.CanConvertFrom(typeof(string)))
{
val = (X)tc.ConvertFromString(value);
}
return val;
}