它必须是 ReadOnlyCollection 吗?我会选择 IEnumerable。
这可以像这样完成,类似于 srsyogesh 的回答:
public abstract class StateMachine
{
public StateMachine(params States[] allowedStates)
{
_allowedStates = allowedStates;
}
private readonly IEnumerable<States> _allowedStates;
public IEnumerable<States> AllowedStates
{
get { return _allowedStates; }
}
}
public class DerivedStateMachine : StateMachine
{
public DerivedStateMachine()
: base(States.State1, States.State2)
{
}
}
当然,仍然可以将 Property 转换回数组并对其进行更改,但那将是一种犯罪行为。取决于你的听众。为了更加防弹,您可以迭代内容,而不仅仅是返回字段:
public IEnumerable<States> AllowedStates
{
get
{
foreach(var state in _allowedStates)
yield return state;
}
}