[英]property.GetValue(dynamictype,null) throw RuntimeBinderException
[英]property.GetValue ignores CultureInfo
似乎由于某种原因,property.GetValue忽略了CultureInfo。 这是我试图实现的目标:
public static IEnumerable<string> GetViewModelProperties(this IDocumentViewModel vm) {
foreach (var property in vm.GetType().GetProperties().Where(p => (p.PropertyType.IsPrimitive ||
p.PropertyType.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))) &&
p.GetIndexParameters().Count() == 0))
{
yield return property.Name + ":" + property.GetValue(vm, System.Reflection.BindingFlags.GetProperty, null, null, System.Globalization.CultureInfo.InvariantCulture);
}
}
我只是使用保存到磁盘
System.IO.File.WriteAllText("filename.txt", settings.ToString());
在结果文件中,属性为double类型的值,值为50.33我得到了
Frequency:50,33
这是CurrentCulture(波兰语使用昏迷作为分隔符),但不是
Frequency:50.33
正如我所料。 什么想法可能是错的?
PropertyInfo的GetValue函数返回一个对象,而不是一个字符串 - 这就是代码中的误解。 该对象被转换为字符串,因为+运算符的第一个参数是字符串(property.Name),但CultureInfo不应用于该字符串转换。
解决方案是显式使用Convert.ToString(object,IFormatProvider)函数,即
yield return property.Name + ":" + Convert.ToString(property.GetValue(vm, System.Reflection.BindingFlags.GetProperty, null, null, System.Globalization.CultureInfo.InvariantCulture), System.Globalization.CultureInfo.InvariantCulture);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.