1

以下是我的 WCF 服务代码的简化版本。此代码工作正常并返回我的数据。

我的问题是,这仅在我通过 ref 或 out 传递客户对象时才有效。如果我修改整个代码以便在没有 ref 或 out 的情况下传递客户对象,则 i 变量中的计数为 0。

如果 List 是一个引用变量,为什么它适用于 ref/out 而没有 ref/out 则不起作用。

另请注意,我将无法从该方法返回一个值,因为我必须返回多个值。

客户代码:

List<Customer> customers = null;
ClientProxy proxy = new ClientProxy();
proxy.GetCustomers(ref customers);
int i = customers.Count;

服务代理:

public class ClientProxy
{
    public void GetCustomers(ref List<Customer> customers)
    {
        INWGetCustomers proxy = new ChannelFactory<INWGetCustomers>("netNamedPipeBinding").CreateChannel();
        proxy.GetCustomers(ref customers);
    }
}

服务合同和数据合同:

[DataContract]
public class Customer
{
    [DataMember]
    public System.String CustomerId;

    [DataMember]
    public System.String CompanyName;
}

[ServiceContract(Namespace = "http://www.temp.com")]
public interface INWGetCustomers
{
    [OperationContract()]
    void GetCustomers(ref List<Customer> customers);
}

服务代码:

public class NWGetCustomersService : INWGetCustomers
{
    public void GetCustomers(ref List<Customer> customers)
    {
        customers = new List<Customer>();
        customers.Add(new Customer() { CustomerId = "1", CompanyName = "A" });
        customers.Add(new Customer() { CustomerId = "2", CompanyName = "B" });
        customers.Add(new Customer() { CustomerId = "3", CompanyName = "C" });
        customers.Add(new Customer() { CustomerId = "4", CompanyName = "D" });
    }
}
4

2 回答 2

1

这是因为在这种情况下使用 ref 或 out 会强制将 list 视为输出参数。它不是真正的通过引用传递,因为对象是在服务器和客户端之间发送的。如果您查看 WSDL,您将看到 .NET 如何生成此代码

总结一下:它在客户端和服务器上不是同一个对象,所以列表是一个引用变量并不重要

于 2013-04-25T05:36:05.860 回答
0

我们必须始终牢记,对对象的引用是按值传递的。调用方法时,它将拥有自己的引用值副本。如果参考值在方法内部发生变化,它不会反映在外部变量中。(我的意思是如果创建了新实例并将相关的参考值分配给方法变量,那么它将不会更新到外部变量)。这就是为什么你必须在你的方法中添加 ref 的原因。执行下面的代码片段。然后在方法签名和调用者中添加 ref 关键字修改代码。你可以意识到差异。

namespace ParameterSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = null;
            GetValue(customer);
            Console.WriteLine("In Main Method : Is customer Null? >>  " + (customer == null));
            Console.Read();
        }
        public static void GetValue(Customer customer)
        {
            customer = new Customer();
            Console.WriteLine("Inside GetValue Method : Is customer Null ? >>  " + (customer == null));
        }
    }
    class Customer
    { }
}
于 2013-04-25T09:38:11.320 回答