在WCF客户端和服务器中使用相同的类
本文关键字:WCF 客户端 服务器 | 更新日期: 2023-09-27 18:28:01
我刚刚在学习wfc,有一个问题。我有写作测试课程:
[DataContract(IsReference = true)]
public class TestClass
{
[DataMember]
public TestKind Kind { set; get; }
[DataMember]
public List<TestClass> Childs { set; get; }
[DataMember]
public TestClass Parent { set; get; }
[DataMember]
public string Id { set; get; }
[DataMember]
public int Value { set; get; }
public TestClass()
{
Childs = new List<TestClass>();
}
}
[DataContract(IsReference = true)]
public class TestKind
{
[DataMember]
public int Id { set; get; }
}
种类存储在缓存中,需要从中加载。目标是在WFC客户端和服务器中使用此类。服务器上没有问题。它很容易启动,并且只有一个方法返回TestClass:的列表
AutoResetEvent infinity = new AutoResetEvent(false);
Uri baseAddress = new Uri("http://localhost:8989/test");
using (ServiceHost host = new ServiceHost(typeof(MyRemote), baseAddress))
{
ServiceMetadataBehavior smb = new ServiceMetadataBehavior
{
HttpGetEnabled = true,
MetadataExporter =
{
PolicyVersion = PolicyVersion.Default
}
};
host.Description.Behaviors.Add(smb);
host.Open();
infinity.WaitOne();
}
服务器实现代码:
[ServiceContract(Name = "testSvc")]
public interface IRemote
{
[OperationContract]
List<TestClass> GetAll();
}
public class Remote : IRemote
{
public List<TestClass> GetAll()
{
return Program.classes;
}
}
但后来我尝试在客户端添加对它的引用,VS创建了一个新的TestClass类,该类具有如下字段:
...
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string IdField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private ConsoleApplication7.ServiceReference1.TestKind KindField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private ConsoleApplication7.ServiceReference1.TestClass ParentField;
...
所以问题是如何对客户端进行编码以连接到服务器并获得TestClass实体的列表(不要生成其他类)。是否可以扩展TestClass?或者其他方法在哪里?
使用[KnownType]
:
[ServiceContract(Name = "testSvc")]
[KnownType(typeof(TestClass))]
public interface IRemote
它将在反序列化期间使用您的类型(而不是创建新类型)-http://msdn.microsoft.com/en-us/library/ms730167(v=vs.110).aspx