首页 文章

如何生成所有datacontract类

提问于
浏览
1

我已经与WCF Build 了聊天服务 . 我有一个标记为datacontract属性的类

[DataContract]
public class Message
{
    string   _sender;
    string   _content;
    DateTime _time;

    [DataMember(IsRequired=true)]
    public string Sender
    {
        get { return _sender;  }
        set { 
            _sender = value;
        }
    }

    [DataMember(IsRequired = true)]
    public string Content
    {
        get { return _content;  }
        set { 
            _content = value;
        }
    }

    [DataMember(IsRequired = true)]
    public DateTime Time
    {
        get { return _time;  }
        set { 
            _time = value;
        }
    }
}

我的服务 Contract 如下

[ServiceContract(Namespace="", SessionMode = SessionMode.Required, CallbackContract = typeof(IChatCallback))]
public interface IChat
{
    [OperationContract]
    bool Connect(Client client);

    [OperationContract(IsOneWay=true, IsInitiating=false, IsTerminating=true)]
    void Disconnect();

    [OperationContract(IsOneWay = true, IsInitiating = false)]
    void Whisper(string target, string message);
}

当我尝试从VisualStudio 2010生成客户端代码时,不会生成类Message . 但是当我将服务 Contract 中方法“Whisper”中的参数“message”的类型更改为Message not string时生成了它 .

我将参数消息的类型更改为“消息”而不是“字符串”:

[OperationContract(IsOneWay = true, IsInitiating = false)]
void Whisper(string target, Message message);

我的回调类需要Message类才能正常工作 .

public interface IChatCallback
{
    void RefreshClient(List<Client> clients);
    void ReceiveWhisper(Message message);
    void ReceiveNotifyClientConnect(Client joinedClient);
    void ReceiveNotifyClientDisconnect(Client leaver);
}

问题是,当它们未包含在服务 Contract 的方法参数或返回值中时,不会生成标记为datacontract属性的类 .

2 回答

  • 1

    服务引用仅生成使用该服务所需的类 . 它不会生成标记为 DataContract 的每个类 .

    但是当我将服务 Contract 中方法“Whisper”中的参数“message”的类型更改为Message not string时生成了它 .

    这正是它应该如何运作的 . 如果服务需要该类,那么它将被生成 . 如果它不需要该类,那么它将不会生成 .

  • 1

    好的,我找到了解决方案 .

    我忘了在回调类中添加operationcontract属性 .

    public interface IChatCallback
    {
        [OperationContract(IsOneWay = true)]
        void RefreshClient(List<Client> clients);
    
        [OperationContract(IsOneWay = true)]
        void ReceiveWhisper(Message message);
    
        [OperationContract(IsOneWay = true)]
        void ReceiveNotifyClientConnect(Client joinedClient);
    
        [OperationContract(IsOneWay = true)]
        void ReceiveNotifyClientDisconnect(Client leaver);
    }
    

相关问题