当我尝试将此类序列化时,我得到一个CommunicationException。 我是否需要使用任何特定的CollectionDataContract标记才能使其正常工作?
[DataContract()]
public class MyClass
{
[DataMember()]
public Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
}
答案 0 :(得分:3)
这应该有用(见下面的例子)。你得到的完整例外是什么?
public class StackOverflow_6966835
{
[DataContract()]
public class MyClass
{
[DataMember()]
public Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
}
[ServiceContract]
public interface ITest
{
[OperationContract]
MyClass GetMyClass();
}
public class Service : ITest
{
public MyClass GetMyClass()
{
return new MyClass
{
dictionary = new Dictionary<string, List<string>>
{
{ "one", "uno un eins".Split().ToList() },
{ "two", "dos deux zwei".Split().ToList() },
{ "three", "tres trois drei".Split().ToList() }
}
};
}
}
public static void Test()
{
Console.WriteLine("Stand-alone serialization");
MemoryStream ms = new MemoryStream();
MyClass c = new Service().GetMyClass();
DataContractSerializer dcs = new DataContractSerializer(typeof(MyClass));
dcs.WriteObject(ms, c);
Console.WriteLine("Serialized: {0}", Encoding.UTF8.GetString(ms.ToArray()));
Console.WriteLine();
Console.WriteLine("Now using in a service");
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
ITest proxy = factory.CreateChannel();
Console.WriteLine(proxy.GetMyClass());
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}