问题描述
考虑如下的类:
公共抽象类令牌
{
私人列表<令牌> _Tokens {获得;组; }
//只读公众是强制性的。如何给受保护的只添加,基于索引的访问?
公共ReadOnlyCollection还<令牌>令牌{{返回(this._Tokens.AsReadOnly()); }}
// AddOnly的派生类。
保护令牌AddToken(令牌令牌){this._Tokens.Add(标记);返程(标记); }
}
公共类ParenthesesToken:令牌
{
//此方法被频繁地从公众code调用。
公共无效解析()
{
// 够好了。
base.AddToken(...);
//是调用列表< T> .AsReadOnly()有必要吗?
//添加只,基于索引的访问是强制性这里。 IEnumerable的< T>不会做。
的foreach(在this.Tokens VAR令牌){/ *做某事* /}
}
}
有一些关于通过列表和ReadOnlyCollection还实现的接口,允许单向型铸造,而不是重新创建列表,其他具体的实现?
我们的目标是让公众只读访问,但也保护了只添加,基于索引的派生类访问。
公共抽象类令牌
{
私人列表<令牌> _tokens {获得;组; }
公开的IEnumerable<令牌>令牌
{
{返回_tokens; }
}
保护令牌AddToken(令牌令牌)
{
_tokens.Add(标记);
返回令牌;
}
保护令牌得到标记(INT指数)
{
回报_tokens [指数]
}
}
我不喜欢返回只读的集合,因为的IEnumerable
是一个只读接口,隐藏实现从消费。有些可以说,消费者可投的IEnumerable
列出并添加新的项目,但是这意味着两件事情:
- 消费你提供的API违反
- 您不能阻止消费者从反射使用
Consider the following classes:
public abstract class Token
{
private List<Token> _Tokens { get; set; }
// ReadOnly public is mandatory. How to give protected add-only, index-based access?
public ReadOnlyCollection<Token> Tokens { get { return (this._Tokens.AsReadOnly()); } }
// AddOnly for derived classes.
protected Token AddToken (Token token) { this._Tokens.Add(token); return (token); }
}
public class ParenthesesToken: Token
{
// This method is called frequently from public code.
public void Parse ()
{
// Good enough.
base.AddToken(...);
// Is a call to List<T>.AsReadOnly() necessary?
// Add-only, indexed-based access is mandatory here. IEnumerable<T> will not do.
foreach (var token in this.Tokens) { /* Do something... */ }
}
}
Is there something about the interfaces implemented by List and ReadOnlyCollection that would allow one-way type casting rather than recreating of the list to other concrete implementations?
The objective is to allow public read-only access but also protected add-only, indexed-based access to derived classes.
public abstract class Token
{
private List<Token> _tokens { get; set; }
public IEnumerable<Token> Tokens
{
get { return _tokens; }
}
protected Token AddToken (Token token)
{
_tokens.Add(token);
return token;
}
protected Token GetTokenAt(int index)
{
return _tokens[index];
}
}
I don't like returning read-only collections, because IEnumerable
is a read-only interface which hides implementation from consumer. Some can argue, that consumer may cast IEnumerable
to list and add new items, but that means two things:
- consumer violates API you provided
- you can't stop consumer from reflection usage
这篇关于个人名单,其中,T&GT;与公众的IEnumerable&LT; T&GT; VS ReadOnlyCollection还&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!