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

C# 限制对方法的访问或为特定对象重写该方法,c#,.net,methods,overriding,visibility,C#,.net,Methods,Overriding,Visibility,(在C#程序中)我有一个列表),而且,如果不保持简单并创建一个继承自列表的新类,我不确定我首先要问的是否可行,我无法访问列表类,因此我无法使该方法成为虚拟的或部分的,或者创建一个隐藏原始方法的溢出 在这种情况下,我如何将现有的Add(objecto)方法设为私有,并用公共方法覆盖它?最好的解决方案是单独的类还是更复杂的类?您想在这个实例中使用新的Add方法来滚动您自己的类 class MyCustomList<T> : List<T> { public new v

(在C#程序中)我有一个
列表),而且,如果不保持简单并创建一个继承自
列表的新类,我不确定我首先要问的是否可行,我无法访问
列表
类,因此我无法使该方法成为虚拟的或部分的,或者创建一个隐藏原始方法的溢出


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

您想在这个实例中使用新的Add方法来滚动您自己的类

class MyCustomList<T> : List<T>
{
    public new void Add(T item)
    {
        //your custom Add code here
        // .... now add it..
        base.Add(item);
    }
}
类MyCustomList:List
{
新增公共作废(T项)
{
//您可以在此处添加自定义代码
//…现在添加它。。
基础。添加(项目);
}
}
用如下方式实例化它:

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

希望这会有所帮助。

我认为最好的解决方案是将列表封装在自己的类中。最好的选择是编写自己的集合,并以列表为后盾。然后可以将自定义逻辑添加到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);
    }
}
公共类AuthorCollection:IList
{
私人IList支持作者列表;
公共AuthorCollection(IList backingAuthorList)
{
if(backingAuthorList==null)
{
抛出新ArgumentNullException(“backingAuthorList”);
}
this.backingAuthorList=backingAuthorList;
}
公共无效添加(作者项)
{
//在这里添加您自己的逻辑
backingAuthorList.Add(项);
}
}

谢谢!我想这行得通。我希望有一些东西不需要创建一个新类,但现在我将使用它。