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

时间:2015-12-15 19:12:39

标签: c# .net methods override visibility

(在C#程序中)我有一个List<Author> authors,其中Author是我写的一个类。 Lists有一个默认的Add(Object o)方法,但我需要让它不太容易访问,或者为特定的authors对象覆盖它。

到目前为止,我已经找到了有关多态性,扩展方法(如here)和this one的信息,但我不确定我是否在询问可以在第一时间保持简单,并创建一个继承自List<Author>的新类(我认为即使 也没有意义,因为我只会使用班级一次)。

请注意,与delegates in combination with dynamic objects不同,我无权访问List<T>类,因此我无法将该方法设为虚拟或部分,或创建隐藏原始方法。

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

2 个答案:

答案 0 :(得分:0)

您希望使用新的Add方法

在此实例中滚动自己的类
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>;

希望有所帮助。

答案 1 :(得分:0)

我认为最好的解决方案是将List封装在自己的类中。最好的选择是编写自己的集合,由列表支持。然后,您可以将自定义逻辑添加到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);
    }
}