了解字典,使用c#向字典中添加新值
本文关键字:字典 添加 新值 使用 了解 | 更新日期: 2023-09-27 18:05:50
如果我有Customer对象,它有Payment属性,它是自定义enum类型的字典和十进制值,如
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);
Add()方法没有返回一个可以分配给cust.Payment
的值,您需要创建字典,然后调用创建的字典对象的Add()方法:
Customer cust = new Customer();
cust.Payment = new Dictionary<CustomerPayingMode,decimal>();
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M);
您可以将字典初始化为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);
到目前为止,我了解cust.Payment
是Dictionary<CustomerPayingMode,decimal>
的类型,但您将其分配给.Add(CustomerPayingMode.CreditCard, 1M)
的结果。
你需要做
cust.Payment = new Dictionary<CustomerPayingMode,decimal>();
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M);
当你调用链方法时,结果是链中最后一个调用的返回值,在你的例子中,是.Add
方法。因为它返回void,所以不能强制转换为Dictionary<CustomerPayingMode,decimal>
您正在创建字典,向其添加一个值,然后将.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);
将值单独添加到您的字典中:
Customer cust = new Customer();
cust.Payment = new Dictionary<CustomerPayingMode, decimal>();
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M);