2016-10-01 109 views
1

我正在使用Visual Studio 2010和.NET 4.0。我創建了一個Web方法,我試圖用複雜對象(類的類對象)作爲參數調用它,但它引發錯誤「對象引用未設置爲對象的實例」。請幫助我如何糾正它。 WCF是如下:如何將複雜對象傳遞給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); 
} 

回答

0

amount.Rate.ExRate = "1255";你想要的值分配給哪個尚未初始化屬性(Rate)線。因此,您不能分配其屬性ExRate

爲了使這項工作,你必須初始化Rate第一:

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

或合併的初始化和賦值:

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

嗨,這是工作。非常感謝。 – sithuwin

+0

不客氣。 – khlr

相關問題