【问题标题】:Is this a good practice to have lightweight object? [closed]这是拥有轻量级对象的好习惯吗? [关闭]
【发布时间】:2020-11-06 06:56:41
【问题描述】:

我是一个网站的开发人员,有很多页面包含列表或 CRUD

为页面列表创建一个只包含所需属性的轻量级对象并创建一个具有更多属性的较重对象是否是一个好习惯,这些属性从创建/更新页面的轻量级对象继承而来?

即使大多数属性为空,总是使用重对象是否会影响性能?

例如:

    class CustomerLight
    {
        int Id { get; set; }
        string FirstName { get; set; }
        string FullName { get; set; }

    }

    class Customer : CustomerLight
    {
        string Adress { get; set; }
        string City { get; set; }
        string ZipCode { get; set; }
    }

    class CustomerFull
    {
        int Id { get; set; }
        string FirstName { get; set; }
        string FullName { get; set; }
        string Adress { get; set; }
        string City { get; set; }
        string ZipCode { get; set; }
    }

【问题讨论】:

    标签: c# asp.net performance


    【解决方案1】:

    您可以从多个角度来处理这个问题。首先我看不出CustomerFullCustomer 之间有什么区别。它们是相同的属性。我怀疑这只是为了比较?

    首先,是的,与小对象相比,较大的对象总是会对性能造成影响。但是,我冒昧地猜测您的数据远没有您注意到它所需的大小。为了便于使用,我将继续使用较大的对象。如果您是从数据库中提取它,那么在代码中使用完整对象会简单得多。

    第二点是,如果您的性能受到影响,那么您总是可以在更强大的机器上运行您的网站(向上扩展)或使用较小的查询大小(重构您的代码)。

    第三点是您可以将这些组件分解为关系结构,以简化您使用的对象并允许以后更好地扩展。我倾向于尝试从将来向该客户添加诸如第二个地址之类的内容的痛苦来考虑我的对象?因此,您可能让客户包含地址列表。为此,如果您打算链接到数据库或仅在代码中使用以下内容,则可以查看 Entity Framework。

    public class Customer {
        public int id { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public List<Address> addresses { get; set; }
    }
    
    public class Address {
        public string Street { get; set; }
        public string Zip { get; set; }
    
    } 
    // Or if 1 to 1 relationship
    public class Customer {
        public int id { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public Address address { get; set; }
    }
    
    public class Address {
        public string Street { get; set; }
        public string Zip { get; set; }
    
    }
    

    希望这有助于回答您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-15
      • 2014-07-01
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多