c# - 从 C# 中的对象类型获取数据

标签 c# wcf

我在服务器端以对象类型存储了一个类对象,并将其发送到客户端。如何从客户端的对象类型中检索类对象的数据成员的数据?我正在使用 WCF 进行通信。我对这个概念很陌生。

Service Contract

  [ServiceContract]
  public interface IRCommService
  {
    [OperationContract]
    result sendMessage(string command, object data);
  }

  [DataContract]
  public class result
  {
    [DataMember]
    public List<string> results { get; set; }
  }


[service behavior]
 public result sendMessage(string command, object data)
    {
      List<string> l = new List<string>();
      Console.WriteLine("Received");
      return new result { results = l };
    }

最佳答案

最好使用自定义请求对象,而不是使用对象数据类型。该请求对象类对于客户端和服务器来说应该是通用的。然后在客户端中,您可以只填写请求并从服务器检索所需的结果.

您的解决方案层次结构最好如下所示。

enter image description here

namespace ServerProj
{
    using System.ServiceModel;
    using Common;

    [ServiceContract]
    public interface IRCommService
    {
        [OperationContract]
        Result SendMessage(string command, CustomRequest data);
    }
}

namespace ServerProj
{
    using System.Collections.Generic;
    using Common;

    public class RCommService : IRCommService
    {
        public Result SendMessage(string command, CustomRequest data)
        {   // You can get the value from here
            int value = data.MyValue;

            Result result = new Result();
            List<string> list = new List<string>();
            list.Add("Sample");
            result.Rsults = list;

            return result;
        }
    }
}

公共(public)程序集中的请求类

namespace Common
{
    using System.Runtime.Serialization;

    [DataContract]
    public class CustomRequest
    {
        [DataMember]
        public int MyValue { get; set; }
    }
}

公共(public)程序集中的响应类

namespace Common
{
    using System.Collections.Generic;
    using System.Runtime.Serialization;

    [DataContract]
    public class Result
    {
        [DataMember]
        public List<string> Rsults { get; set; }
    }
}

然后只需在客户端添加为服务引用即可。

private void button1_Click(object sender, EventArgs e)
        {
            ServiceReference1.RCommServiceClient service = new ServiceReference1.RCommServiceClient();
            CustomRequest customRequest=new CustomRequest();
            customRequest.MyValue = 10;

            Result result = service.SendMessage("Test", customRequest);
        }

关于c# - 从 C# 中的对象类型获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19886320/

相关文章:

c# - 我的数据绑定(bind)怎么会写出 Length 属性?

c# - MF SinkWriter写入样本失败

wcf - 自定义工具警告: An item with the same key has already been added

c# - 需要保护 WCF 数据,但只是一个部分

WCF - 序列化继承的类型

c# - IE 子域登录在登录父域时不起作用

c# - 具有空间数据的 Hololens 视频流

c# - Windows 商店中的非公共(public)成员(member)访问权限

asp.net - WCF REST 服务模板 40 和 JSON 格式的 Entity Framework 返回空响应

c# - 如何最大化大对象堆中最大的连续内存块