我正在尝试使用 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, andPresentationFramework
assembly.The
System.Xaml
implementation is found in theSystem.Xaml
namespace.If you are using WPF types or are deriving from WPF types, you should typically use the WPF implementations of
XamlReader
andXamlWriter
instead of theSystem.Xaml
implementations.For more information, see Remarks in
System.Windows.Markup.XamlReader
andSystem.Windows.Markup.XamlWriter
.
关于c# - 使用 XamlWriter 保存数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12840203/