通常我会返回一个数据数组而不是集合类型。例如,在C#中,许多集合实现了.toArray()方法,对于那些没有的,可以使用lambda表达式来检索数组。
编辑:
看到你对"No Refunds No Returns"答案的评论。如果你正在返回一个字典,那么数组可能不适用于你。在这种情况下,我建议返回一个接口而不是具体的实现。
在C#中(例如):
public IDictionary<string, object> MyMethod()
{
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
return myDictionary;
}
编辑2
您可能需要实现自己的只读字典类,并在必要的方法中抛出异常以防止添加等操作。
在C#中(例如)(不是完整的解决方案):
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private IDictionary<TKey, TValue> _innerDictionary;
public ReadOnlyDictionary(IDictionary<TKey, TValue> innerDictionary)
{
this._innerDictionary = innerDictionary;
}
public void Add(TKey key, TValue value)
{
throw new NotImplementedException();
}
public bool Remove(TKey key)
{
throw new NotImplementedException();
}
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _innerDictionary.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _innerDictionary.GetEnumerator();
}
}