C# 无法将对象添加到字典中
我得到了一个带有列表的代码,我正试图把它改成字典。我的问题是,在“BankRates.cs”中,我无法将对象添加到字典中。我收到的消息“Converter.CurrencyDic”没有包含“Add”的定义…有人能解释一下原因吗 我有4个cs文件:C# 无法将对象添加到字典中,c#,.net,linq,dictionary,C#,.net,Linq,Dictionary,我得到了一个带有列表的代码,我正试图把它改成字典。我的问题是,在“BankRates.cs”中,我无法将对象添加到字典中。我收到的消息“Converter.CurrencyDic”没有包含“Add”的定义…有人能解释一下原因吗 我有4个cs文件: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Converter
{
class Currency
{
//members
//getters and setters
public string Code { get; set; }
public string Name { get; set; }
public double Rate { get; set; }
public double Unit { get; set; }
public string Country { get; set; }
//constractor
public Currency(string code, string name, double rate, double unit, string country)
{
this.Code = code;
this.Name = name;
this.Rate = rate;
this.Unit = unit;
this.Country = country;
}
//override ToString method for visualization
public override string ToString()
{
return (Name + "-" +Code);
}
}
}
货币词典:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Converter
{
class CurrencyDic
{
//setter and getter
public Dictionary<string,Currency> currencyDic { get; set; }
//constractor
public CurrencyDic()
{
currencyDic = new Dictionary<string,Currency>();
}
public CurrencyDic(Dictionary<string,Currency> cur)
{
currencyDic = new Dictionary<string,Currency>(cur);
}
// implements foreach
public IEnumerator<Currency> GetEnumerator()
{
foreach (Currency cur in currencyDic.Values) { yield return cur;}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Converter
{
interface IBankRates
{
void GetRates();
double Convert(Currency from, Currency to, double amount);
}
}
您的
CurrencyDict
类封装了一个词典
,而不是继承一个
您需要在类中使用字典
的Add
方法:
foreach (var currency in allCurencies)
{
currencyDic.currencyDic.Add(new Currency(currency.Code, currency.Name,
double.Parse(currency.Rate),
double.Parse(currency.Unit), currency.Cuntry));
}
也许您应该尝试更改局部变量的名称,这样您就不会感到困惑。因为您的
CurrencyDictionary
类没有add方法?你怎么会这么认为呢?我试了你的建议,但得到了这个错误:错误2方法“Add”没有重载需要1个参数
foreach (var currency in allCurencies)
{
currencyDic.currencyDic.Add(new Currency(currency.Code, currency.Name,
double.Parse(currency.Rate),
double.Parse(currency.Unit), currency.Cuntry));
}