没有添加的公共列表

Nic*_*ron 7 c# list readonly-collection

public class RegistrationManager
{
  public List<object> RegisteredObjects;

  public bool TryRegisterObject(object o) 
  {
    // ...
    // Add or not to Registered
    // ...
  }
} 
Run Code Online (Sandbox Code Playgroud)

我希望RegisterObjects可以从课堂外访问,但是填充RegisterObjects列表的唯一方法是通过TryRegisterObject(object o).

这可能吗 ?

Art*_*iom 5

我会将它隐藏在ReadonlyCollection下。例如,在这种情况下,客户端将无法通过强制转换为 IList 来添加元素。这完全取决于您想要的安全程度(在最简单的情况下,暴露 IEnumerable 就足够了)。

public class RegistrationManager
{
  private List<object> _registeredObjects;
  ReadOnlyCollection<object> _readOnlyRegisteredObjects;

  public RegistrationManager()
  {
      _registeredObjects=new List<object>();
      _readOnlyRegisteredObjects=new ReadOnlyCollection<object>(_registeredObjects);
  }

  public IEnumerable<object> RegisteredObjects
  {
     get { return _readOnlyRegisteredObjects; }
  }


  public bool TryRegisterObject(object o) 
  {
    // ...
    // Add or not to Registered
    // ...
  }
} 
Run Code Online (Sandbox Code Playgroud)