理解字典,使用c#向字典添加新值

use*_*862 4 c# dictionary initialization

如果我的Customer对象具有Payment属性,它是自定义枚举类型和十进制值的字典

Customer.cs
public enum CustomerPayingMode
{
   CreditCard = 1,
   VirtualCoins = 2, 
   PayPal = 3
}
public Dictionary<CustomerPayingMode, decimal> Payment;
Run Code Online (Sandbox Code Playgroud)

在客户端代码中,我有向字典添加值的问题,尝试这样

Customer cust = new Customer();
cust.Payment = new Dictionary<CustomerPayingMode,decimal>()
                      .Add(CustomerPayingMode.CreditCard, 1M);
Run Code Online (Sandbox Code Playgroud)

Clo*_*ble 6

添加()梅索德不回,你可以分配到一个值cust.Payment,你需要创建字典,然后调用创建Dictionary对象的Add()梅索德:

Customer cust = new Customer();
cust.Payment = new Dictionary<CustomerPayingMode,decimal>();
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M);
Run Code Online (Sandbox Code Playgroud)