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

时间:2013-03-25 13:10:56

标签: c# dictionary initialization

如果我的Customer对象具有Payment属性,该属性是自定义枚举类型和小数值的字典,如

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

在客户端代码中,我在向Dictionary添加值时遇到了问题,尝试过这样的

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

5 个答案:

答案 0 :(得分:6)

Add()方法不返回可以赋值给cust.Payment的值,需要创建字典然后调用创建的Dictionary对象的Add()方法:

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

答案 1 :(得分: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);

答案 2 :(得分: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>

答案 3 :(得分:0)

您正在创建字典,为其添加值,然后将.Add函数的结果返回给您的变量。

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);

答案 4 :(得分:0)

在单独的行中向字典添加值:

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