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

4

如果我有一个客户对象,其中有一个Payment属性,它是一个由自定义枚举类型和十进制值组成的字典,例如

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
@Lunivore,那是一次无效的编辑。 - CloudyMarble
哦,真的吗?好的,那有更好编辑经验的人可以加上一个实际的问题吗? - Lunivore
5个回答

6

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

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

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

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
你正在创建一个字典,向其中添加一个值,然后将.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);

0
在一个单独的行上向你的字典添加值:
    Customer cust = new Customer();
    cust.Payment = new Dictionary<CustomerPayingMode, decimal>();
    cust.Payment.Add(CustomerPayingMode.CreditCard, 1M);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接