4

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

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

5 回答 5

6

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

Customer cust = new Customer();
cust.Payment = new Dictionary<CustomerPayingMode,decimal>();
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M);
于 2013-03-25T13:12:32.837 回答
2

您可以内联初始化字典

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);
于 2013-03-25T13:13:23.323 回答
1

到目前为止,我理解cust.Payment的是 type ofDictionary<CustomerPayingMode,decimal>但您将其分配为.Add(CustomerPayingMode.CreditCard, 1M).

你需要做

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

当您链接方法调用时,结果是链中最后一个调用的返回值,在您的情况下是.Add方法。由于它返回 void,因此无法转换为Dictionary<CustomerPayingMode,decimal>

于 2013-03-25T13:13:40.067 回答
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);
于 2013-03-25T13:13:25.370 回答
0

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

    Customer cust = new Customer();
    cust.Payment = new Dictionary<CustomerPayingMode, decimal>();
    cust.Payment.Add(CustomerPayingMode.CreditCard, 1M);
于 2013-03-25T13:37:20.867 回答