如何将复杂对象传递给WCF

时间:2016-10-01 09:32:26

标签: .net wcf

我正在使用Visual Studio 2010和.NET 4.0。我创建了一个Web方法,我试图用复杂的对象(类的类对象)作为参数调用它,但它引发错误“对象引用未设置为对象的实例”。请帮我解决一下。 WCF如下:

[ServiceContract]
public interface IService
{
    [OperationContract]
    void DoWork();

     [OperationContract]
    void RedirectDeposit(string TransactionId, Amount amount);
}

public class Service : IService
{
    public void DoWork()
    {

    }

    public void RedirectDeposit(string TransactionId, Amount amount)
    {
        string transactionId = "";
        string tranAmount = "";
        string tranCurrency = "";
        string exchangeRate = "";

        try
        {
            transactionId = TransactionId;
            tranAmount = amount.Amt;
            tranCurrency = amount.Currency;
            exchangeRate = amount.Rate.ExRate;
        }
        catch (Exception ex)
        {
            Utility.LogMsg("Amount : " + ex.Message);
        }

    }
}

[DataContract]
public class Amount
{
    [DataMember]
    public string Amt { get; set;  }
    [DataMember]
    public string Currency {get; set; }
    [DataMember]
    public ExchangeRate Rate { get; set; }

}

[DataContract]
public class ExchangeRate
{
    [DataMember]
    public string ExRate { get; set; }

}

客户来电如下:

playtechsrv.ServiceClient service = new ServiceClient();
Amount amount = new Amount();

try
{
      // Put user code to initialize the page here
      amount.Amt = "10";
      amount.Currency = "USD";
      amount.Rate.ExRate = "1255"; // Error happen here

}
catch (Exception ex)
{
      Utility.LogMsg(ex.Source);
}

1 个答案:

答案 0 :(得分:0)

amount.Rate.ExRate = "1255";行中,您尝试将值分配给尚未初始化的属性(Rate)。因此,您无法指定其属性ExRate

为了完成这项工作,您必须首先初始化Rate

amount.Rate = new ExchangeRate();
amount.Rate.ExRate = "1255";

或者结合初始化和分配:

amount.Rate = new ExchangeRate { ExRate = "1255" };