2013-03-25 74 views
4

如果我有一個有支付物業的客戶對象,它是自定義枚舉類型和十進制值的字典一樣瞭解字典,使用C#添加新值到字典

Customer.cs 
public enum CustomerPayingMode 
{ 
    CreditCard = 1, 
    VirtualCoins = 2, 
    PayPal = 3 
} 
public Dictionary<CustomerPayingMode, decimal> Payment; 

在客戶端代碼中,我有問題,增加值在字典中,嘗試這樣

Customer cust = new Customer(); 
cust.Payment = new Dictionary<CustomerPayingMode,decimal>() 
         .Add(CustomerPayingMode.CreditCard, 1M); 
+2

那麼* *什麼問題呢? – Arran 2013-03-25 13:12:52

+4

@Lunivore那是一個無效的編輯。 – CloudyMarble 2013-03-25 13:17:48

+0

嗯,真的嗎?好的;可以有誰更好的編輯想法添加一個實際的問題,然後,請? – Lunivore 2013-03-25 13:20:05

回答

6

Add()梅索德不返回值可以分配給cust.Payment,您需要創建字典,然後調用創建Dictionary對象的Add()梅索德:

Customer cust = new Customer(); 
cust.Payment = new Dictionary<CustomerPayingMode,decimal>(); 
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M); 
2

你可以initialize the dictionary inline

Customer cust = new Customer(); 
cust.Payment = new Dictionary<CustomerPayingMode, decimal>() 
{ 
    { CustomerPayingMode.CreditCard, 1M } 
}; 

您可能還需要初始化Customer構造內的字典,讓用戶添加到Payment無需初始化詞典:

public class Customer() 
{ 
    public Customer() 
    { 
     this.Payment = new Dictionary<CustomerPayingMode, decimal>(); 
    } 

    // Good practice to use a property here instead of a public field. 
    public Dictionary<CustomerPayingMode, decimal> Payment { get; set; } 
} 

Customer cust = new Customer(); 
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M); 
+0

適用於最佳做法 – JeffO 2013-03-25 13:44:12

0

您正在創建字典,爲其添加一個值,然後返回的結果3210函數給你的變量。

Customer cust = new Customer(); 

// Set the Dictionary to Payment 
cust.Payment = new Dictionary<CustomerPayingMode, decimal>(); 

// Add the value to Payment (Dictionary) 
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M); 
1

到目前爲止,我明白cust.PaymentDictionary<CustomerPayingMode,decimal>類型,但你分配給它的.Add(CustomerPayingMode.CreditCard, 1M)結果。

你需要做的

cust.Payment = new Dictionary<CustomerPayingMode,decimal>(); 
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M); 

當鏈的方法調用,其結果是在鏈中的最後一次調用的返回值,你的情況,.Add方法。由於它返回void,它不能轉換爲Dictionary<CustomerPayingMode,decimal>

0

值,你的字典添加一個單獨的行:

Customer cust = new Customer(); 
    cust.Payment = new Dictionary<CustomerPayingMode, decimal>(); 
    cust.Payment.Add(CustomerPayingMode.CreditCard, 1M);