c# - 使用 XamlWriter 保存数组

标签 c# arrays xaml xamlwriter

我正在尝试使用 XamlWriter 保存一组对象以最简单的方式。由于某种原因,将它们保存为数组会产生无效的 XML:

var array = new int[] {1, 2, 3};
Console.Write(XamlWriter.Save(array));

输出:

<Int32[] xmlns="clr-namespace:System;assembly=mscorlib">
   <Int32>1</Int32>
   <Int32>2</Int32>
   <Int32>3</Int32>
</Int32[]>

尝试使用 XamlReader 阅读此内容抛出:

The '[' character, hexadecimal value 0x5B, cannot be included in a name. Line 1, position 7

我试过保存为 List<T>相反,但我得到了通常的 XAML 泛型错误。是否有一些简单的方法可以做到这一点(最好使用 LINQ)或者我是否必须定义自己的包装器类型?

最佳答案

XamlWriter.Save产生无效的 XML。

<Int32[] xmlns="clr-namespace:System;assembly=mscorlib">
   <Int32>1</Int32>
   <Int32>2</Int32>
   <Int32>3</Int32>
</Int32[]>

我不知道这背后的原因,但使用 XamlServices.Save似乎解决了这个问题。

<x:Array Type="x:Int32" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <x:Int32>1</x:Int32>
  <x:Int32>2</x:Int32>
  <x:Int32>3</x:Int32>
</x:Array>

来自 MSDN 的附加说明

The following classes exist in both the WPF assemblies and the System.Xaml assembly in the .NET Framework 4:

  • XamlReader
  • XamlWriter
  • XamlParseException

The WPF implementation is found in the System.Windows.Markup namespace, and PresentationFramework assembly.

The System.Xaml implementation is found in the System.Xaml namespace.

If you are using WPF types or are deriving from WPF types, you should typically use the WPF implementations of XamlReader and XamlWriter instead of the System.Xaml implementations.

For more information, see Remarks in System.Windows.Markup.XamlReader and System.Windows.Markup.XamlWriter.

关于c# - 使用 XamlWriter 保存数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12840203/

相关文章:

javascript - 从 JavaScript 中的文本返回数组

c# - WPF自定义控件库图片资源

c# - 在 C# 中使用 XML 文件创建 GUI

c# - 在 Windows Phone 8.1 Universal Store App 中触发警报?

Javascript 将 JSON 字符串转换为数组的数组

c - C 中将 malloc 的 2d 数组修改为 3d 数组的函数

c# - DrawingImage 样式绑定(bind)错误

c# - XAML 和 MySQL 数据库访问

C# 在每个 # 符号后拆分字符串

c# - ASP.NET MVC 应用程序无法访问路径错误