【问题标题】:Accessing inherited properties through a static class通过静态类访问继承的属性
【发布时间】:2010-11-12 21:47:01
【问题描述】:

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

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

我想要实现的只是访问 List 的所有属性。

在课堂之外,我希望能够做到以下几点:

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

谢谢!

【问题讨论】:

  • 你的Add不是无限递归吗?

标签: c# asp.net oop inheritance static


【解决方案1】:

两件事:

1) 不要继承List&lt;T&gt;。实现IList&lt;T&gt;

2) 使用单例:

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

    private CartCollection() { }

    // Implement IList<T> here
}

此外,当您在 ASP.NET 应用程序中使用它时,您应该知道静态成员由 所有 请求共享。在没有locking 的情况下适当地使用这种代码可能会导致崩溃。即使您使用lock,您也会在您的用户之间共享数据,这可能是您不希望的……

【讨论】:

    【解决方案2】:

    不要从List&lt;&gt;继承,嵌入一个:

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

    【讨论】:

    • _list 的声明中缺少变量名。
    【解决方案3】:

    为什么要子类 List 呢?如果您不添加其他功能,为什么不直接使用List&lt;Cart&gt;

    public static class CartCollection
    {
        public static readonly List<Cart> Instance = new List<Cart>();
    }
    
    Cart cart = new Cart();
    cart.SomeProperty = 0;
    CartCollection.Instance.Add(cart);
    

    【讨论】:

    • 你的代码已经足够好了,但我想,使用Design Patterns 总是被认为是good programming practice
    猜你喜欢
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2011-04-16
    • 2012-03-30
    • 2017-09-01
    • 2016-10-10
    • 2011-06-24
    相关资源
    最近更新 更多