通过WCF提供类对象的数组或列表

时间:2012-08-21 10:27:54

标签: c# .net wcf abstraction svcutil.exe

WCF客户端服务器提供List或Array自定义类对象的任何示例都会对我有帮助!但这是我到目前为止所做的:

这是我要提供的班级系统

namespace NEN_Server.FS {
    [Serializable()]
    public class XFS {
        private List<NFS> files;
        public XFS() {
            files = new List<NFS>();
            }
        public List<NFS> Files {
            get { return files; }
            set { files = value; }
            }
        }
    }

NFS是

namespace NEN_FS {
    public interface INFS : IEquatable<NFS> {
        string Path { get; set; }
        }
    [Serializable()]
    abstract public class NFS : INFS {
        abstract public string Path { get; set; }
        public NFS() {
            Path = "";
            }
        public NFS(string path) {
            Path = path;
            }
        public override bool Equals(object obj) {
            NFS other = obj as NFS;
            return (other != null) && ((IEquatable<NFS>)this).Equals(other);
            }
        bool IEquatable<NFS>.Equals(NFS other) {
            return Path.Equals(other.Path);
            }
        public override int GetHashCode() {
            return Path != null ? Path.GetHashCode() : base.GetHashCode();
            }
        }
    }

并提供方法是:

namespace NEN_Server.WCF {
    public class NEN : INEN {
        private MMF mmf;
        public NEN() {
            mmf = new MMF();
            }
        public string GetRandomCustomerName() {
            return mmf.MMFS.Files[0].Path;
            }
        public NFS[] ls() {
            return mmf.MMFS.Files.ToArray();
            }

界面

<ServiceContract>
Public Interface INEN
    <OperationContract>
    Function GetRandomCustomerName() As String
    <OperationContract()>
    Function ls() As NFS()

最后我做了:

%svcutil% /language:cs /out:NEN_Protocol\NEN.cs http://localhost:8080/NEN_Server

它生成:

public NEN_FS.NFS[] ls()
{
    return base.Channel.ls();
}

我在我的客户端应用程序let files = nen.ls()中调用它,但它失败了:

An unhandled exception of type 'System.ServiceModel.CommunicationException' occurred in mscorlib.dll

Additional information: The underlying connection was closed: The connection was closed unexpectedly.

return base.Channel.ls();代码行上。

注意提供字符串mmf.MMFS.Files[0].Path;的工作正常

为什么呢?我究竟做错了什么? :)

GitHub上提供了所有代码:https://github.com/nCdy/NENFS

1 个答案:

答案 0 :(得分:2)

在我看来,错误的原因在于:abstract public class NFS 首先,考虑将data contracts与WCF一起使用:

[DataContract(IsReference = true)]
abstract public class NFS : INFS 
{
  [DataMember]
  abstract public string Path { get; set; }

  // the rest of code here
}

第二个,为您的数据合同指定known types。通信渠道两侧的序列化程序必须知道如何对具体NFS'后代类型进行seralize / deserialize:

[DataContract(IsReference = true)]
[KnownType(typeof(NFS1))]
[KnownType(typeof(NFS2))]
abstract public class NFS : INFS 
{
  [DataMember]
  abstract public string Path { get; set; }

  // the rest of code here
}

public class NFS1 : NFS {}
public class NFS2 : NFS {}