C# 通过静态类访问继承的属性

C# 通过静态类访问继承的属性,c#,asp.net,oop,inheritance,static,C#,Asp.net,Oop,Inheritance,Static,目前,我正在通过创建一个静态方法来访问该属性,如下所示 public static class CartCollection : List<Cart> { public static void Add(Cart Cart) { Add(Cart); } } 谢谢 有两件事: 1) 不要继承列表。实现IList 2) 使用单例: public class CartCollection : IList<Cart> { publ

目前,我正在通过创建一个静态方法来访问该属性,如下所示

public static class CartCollection : List<Cart>
{
    public static void Add(Cart Cart)
    {
        Add(Cart);
    }
}
谢谢

有两件事:

1) 不要继承
列表
。实现IList

2) 使用单例:

public class CartCollection : IList<Cart>
{
    public static readonly CartCollection Instance = new CartCollection();

    private CartCollection() { }

    // Implement IList<T> here
}
公共类集合:cartilist
{
公共静态只读CartCollection实例=新建CartCollection();
私有CartCollection(){}
//在这里实现IList
}

另外,当您在ASP.NET应用程序中使用此功能时,您应该知道所有请求都共享静态成员。使用此类代码而不适当地
锁定
可能会导致崩溃。即使您使用了
lock
,您也会在用户之间共享数据,这可能是您不希望的…

不要从
列表继承,请嵌入一个:

public static class CartCollection
{
    private static List<Cart> _list = new List<Cart>();

    public static void Add(Cart Cart)
    {
        _list.Add(Cart);
    }
}
公共静态类集合
{
私有静态列表_List=新列表();
公共静态无效添加(购物车)
{
_列表。添加(购物车);
}
}

为什么要列出子类?如果不添加其他功能,为什么不直接使用
List

公共静态类集合
{
公共静态只读列表实例=新列表();
}
购物车=新购物车();
cart.SomeProperty=0;
CartCollection.Instance.Add(购物车);

你的
Add
不是一个无休止的递归吗?你在
\u list
的声明中缺少了变量名。你的代码已经足够好了,但是我想,使用
设计模式
总是被认为是一种
好的编程实践
public static class CartCollection
{
    private static List<Cart> _list = new List<Cart>();

    public static void Add(Cart Cart)
    {
        _list.Add(Cart);
    }
}
public static class CartCollection
{
    public static readonly List<Cart> Instance = new List<Cart>();
}

Cart cart = new Cart();
cart.SomeProperty = 0;
CartCollection.Instance.Add(cart);