在WCF客户端和服务器中使用相同的类

时间:2014-10-26 11:11:30

标签: c# wcf

我只是在学习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吗?或者其他方法在哪里?

1 个答案:

答案 0 :(得分:0)

使用[KnownType]

[ServiceContract(Name = "testSvc")]
[KnownType(typeof(TestClass))]
public interface IRemote

这将在反序列化期间使用您的类型(而不是创建新类型) - http://msdn.microsoft.com/en-us/library/ms730167(v=vs.110).aspx