Private <T> list with public IEnumerable <T> vs ReadOnlyCollection <T>
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 anything in the interfaces implemented by List and ReadOnlyCollection that would allow us to use a one-way type rather than recreate the list for other specific implementations?
The goal is to allow read-only public access, as well as secure access only for indexed access to derived classes.
+1
1 answer
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];
}
}
, IEnumerable - , . , IEnumerable , :
- API
- .
+3