我的问题之后 Problem with implementation own version of KeyValuePair<TKey, TValue> 现在我不会更改课程代码
public class VectorType<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
string variableName;
Dictionary<TKey, TValue> paramteresList;
public VectorType(string variableName)
{
this.variableName = variableName;
paramteresList = new Dictionary<TKey, TValue>();
}
public void Add(TKey parameterName, TValue parametereValue)
{
paramteresList.Add(parameterName, parametereValue);
}
public int NumberOfParameters
{
get { return paramteresList.Count; }
}
public string VariableName
{
get { return variableName; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)paramteresList).GetEnumerator();
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return paramteresList.GetEnumerator();
}
}
将我自己的KeyValuePair实现用作
public struct ParameterNameKeyValuePair<TParameterNameKey, TValue>
{
private TParameterNameKey key;
private TValue value;
public ParameterNameKeyValuePair(TParameterNameKey key, TValue value)
{
this.key = key;
this.value = value;
}
public TParameterNameKey Key
{
get { return key; }
}
public TValue Value
{
get { return value; }
}
}
如果我将KeyValuePair更改为ParameterNameKeyValuePair我有
public class VectorType<TParameterNameKey, TValue> : IEnumerable<ParameterNameKeyValuePair<TParameterNameKey, TValue>>
{
string variableName;
Dictionary<TParameterNameKey, TValue> paramteresList;
public VectorType(string variableName)
{
this.variableName = variableName;
paramteresList = new Dictionary<TParameterNameKey, TValue>();
}
public void Add(TParameterNameKey parameterName, TValue parametereValue)
{
paramteresList.Add(parameterName, parametereValue);
}
public int NumberOfParameters
{
get { return paramteresList.Count; }
}
public string VariableName
{
get { return variableName; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)paramteresList).GetEnumerator();
}
IEnumerator<ParameterNameKeyValuePair<TParameterNameKey, TValue>> IEnumerable<ParameterNameKeyValuePair<TParameterNameKey, TValue>>.GetEnumerator()
{
return paramteresList.GetEnumerator();
}
}
,我在编译时出错:无法隐式转换类型
从'System.Collections.Generic.Dictionary.Enumerator'到'System.Collections.Generic.IEnumerator>'
IEnumerator<ParameterNameKeyValuePair<TParameterNameKey, TValue>> IEnumerable<ParameterNameKeyValuePair<TParameterNameKey, TValue>>.GetEnumerator()
{
return paramteresList.GetEnumerator();
}
我只将KeyValuePair更改为ParameterNameKeyValuePair。我有这个错误吗?第二个问题,像在我的情况下ParameterNameKeyValuePair那样实现自己的KeyValuePair是安全的吗?