我在服务器端以对象类型存储了一个类对象,并将其发送到客户端。如何从客户端的对象类型中检索类对象的数据成员的数据?我正在使用 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 };
}
最佳答案
最好使用自定义请求对象,而不是使用对象数据类型。该请求对象类对于客户端和服务器来说应该是通用的。然后在客户端中,您可以只填写请求并从服务器检索所需的结果.
您的解决方案层次结构最好如下所示。
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/