如何制作一个可以添加到 Windows.Foundation.Collections.ValueSet 的类

Mas*_*vey 6 c# uwp

我正在制作一个 UWP 应用程序,它利用AppServiceConnection将数据发送到 COM 风格的应用程序。在AppServiceConnection.SendMessageAsync()需要类型的Windows.Foundation.Collections.ValueSet

ValueSet 类是一个集合,类似于存储 KeyValuePairs 类型的字典 <string, object>

我在向 ValueSet 添加数据时遇到问题,每次尝试添加对象时都会收到错误消息:“不支持这种类型的数据。(来自 HRESULT 的异常:0x8007065E)”

对此错误的研究表明,要添加的对象必须是可序列化的类型,并且可以实现Windows.Foundation.Collections.IPropertySet其本身是一个似乎存储键值对的集合接口。

我想知道如何制作一个可以添加到 ValueSet 的类。我是否必须创建一个新的集合来实现,IPropertySet或者有什么方法可以使类本身可序列化并能够添加到 ValueSet 中?

如果我必须实施IPropertySet,谁能指出我有关如何执行此操作的体面文档?

Pet*_*SFT 5

WinRT 没有可序列化对象的概念;它只支持整数、布尔值、字符串、数组、日期时间等值类型以及这些类型的集合。查看Create*的静态成员的示例(尽管您不需要使用这些方法来创建放入集合中的项目)。PropertyValue

如果要序列化 ​​WinRT 对象或您自己的 .NET 对象,可以将其转换为 JSON 或 XML,然后将其放入ValueSet.

例如:

  public void TestValueSet()
  {
    var x = new ValueSet();

    // Integers are OK
    x.Add("a", 42);

    // URIs are not OK - can't be serialized
    try
    {
      x.Add("b", new Uri("http://bing.com"));
    }
    catch (Exception ex)
    {
      Debug.WriteLine("Can't serialize a URI - " + ex.Message);
    }

    // Custom classes are not OK
    var myClass = new MyClass { X = 42, Y = "hello" };
    try
    {
      x.Add("c", myClass);
    }
    catch (Exception ex)
    {
      Debug.WriteLine("Can't serialize custom class - " + ex.Message);
    }

    // Serialized classes are OK
    x.Add("d", Serialize<MyClass>(myClass));

    foreach (var kp in x)
    {
      Debug.WriteLine("{0} -> {1}", kp.Key, kp.Value);
    }
  }

  string Serialize<T>(T value)
  {
    var dcs = new DataContractSerializer(typeof(T));
    var stream = new MemoryStream();
    dcs.WriteObject(stream, value);
    stream.Position = 0;
    var buffer = new byte[stream.Length];
    stream.Read(buffer, 0, (int)stream.Length);
    return Encoding.UTF8.GetString(buffer);
  }
}

[DataContract]
public class MyClass
{
  [DataMember]
  public int X { get; set; }
  [DataMember]
  public string Y { get; set; }
}
Run Code Online (Sandbox Code Playgroud)