【问题标题】:property.GetValue ignores CultureInfoproperty.GetValue 忽略 CultureInfo
【发布时间】:2013-10-11 06:23:46
【问题描述】:

似乎由于某种原因 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());

在生成的文件中,对于值为 50.33 的 double 类型的属性频率,我得到了

Frequency:50,33

这是CurrentCulture(波兰语使用逗号作为分隔符),但不是

Frequency:50.33

正如我所料。有什么想法可能是错的吗?

【问题讨论】:

    标签: c# reflection invariantculture


    【解决方案1】:

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多