限制对方法的访问或为特定对象重写该方法

Restricting Access to a Method or Rewriting that Method for a Specific Object

(在 C# 程序中)我有一个 List<Author> authors,其中 Author 是我写的 class。 Lists 有一个默认的 Add(Object o) 方法,但我需要让它更难访问或覆盖它,专门用于我的 authors 对象。

到目前为止,我已经找到了有关多态性、扩展方法的信息(例如 this one), and delegates in combination with dynamic objects,但我不确定我首先要问的问题是否可以在不保持简单和创建的情况下实现一个继承自 List<Author> 的新 class(我认为即使 that 也没有意义,因为我只会使用 class 一次).

请注意,与 this scenario 不同,我无权访问 List<T> class,因此我无法将方法设为虚拟或部分方法,或创建溢出隐藏原始方法。

鉴于这种情况,我如何将现有的 Add(Object o) 方法设为私有并用 public 方法覆盖它?最好的解决方案是单独的 class 还是更复杂的东西?

你想在这个实例中使用新的添加方法

滚动你自己的class
class MyCustomList<T> : List<T>
{
    public new void Add(T item)
    {
        //your custom Add code here
        // .... now add it..
        base.Add(item);
    }
}

用这样的东西实例化它:

MyCustomList<Author> sam = new MyCustomList<Author>;

希望对您有所帮助。

我认为最好的解决方案是将 List 封装在它自己的 class 中。最好的选择是编写自己的集合,并以列表为后盾。然后您可以将自定义逻辑添加到 add 方法中。

示例:

public class AuthorCollection : IList<Author>
{
    private IList<Author> backingAuthorList;

    public AuthorCollection(IList<Author> backingAuthorList)
    {
        if (backingAuthorList == null)
        {
            throw new ArgumentNullException("backingAuthorList");
        }

        this.backingAuthorList = backingAuthorList;
    }

    public void Add(Author item)
    {
        // Add your own logic here

        backingAuthorList.Add(item);
    }
}