Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Class 如果不获取嵌套类的集合,那么嵌套类的优点是什么?_Class_Oop_Poco - Fatal编程技术网

Class 如果不获取嵌套类的集合,那么嵌套类的优点是什么?

Class 如果不获取嵌套类的集合,那么嵌套类的优点是什么?,class,oop,poco,Class,Oop,Poco,我见过一些这样的例子: 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 s

我见过一些这样的例子:

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 City { get; set; }
}
我仍然不知道与以下各项相比有什么优势:

public class Customer
{
 public int ID { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string Street { get; set; }
 public string City { get; set; } 
}
有什么想法吗


干杯。

您的类不是嵌套的,它只是使用组合。合成是从一个或多个其他类合成一个类。它的优点当然是重用

您可以在另一个类或方法中使用
Address
类,还可以封装
Address
类中必须包含的所有逻辑和数据

如果需要嵌套类,则可以将其编写为:

public class Apple
{
    public int Mass;
    public Worm MyWorm;

    public class Worm
    {
         public string Name;
    }
}

您展示的示例不是嵌套类,而是通过组合使用另一个类的属性

示例中的主要优点是
地址是一个单独的
实体(重构),并可用于指示
给定
客户的地址
,例如客户可能有
家
地址
,一个
业务地址
和一个
公司地址
,它们都是 将属于
地址类型
类别

在没有单独的
地址
类的情况下实现上述分类是很困难的,否则这就是将
地址
作为单独类进行分类的原因之一

例如,您的
Customer
类可以进行如下修改,以显示其优点之一:

public class Customer
{
     public int ID { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public Address HomeAddress { get; set; }
     public Address BusinessAddress { get; set; }
     public Address CorporateAddress { get; set; }
}

现在,根据上面的示例,如果您的
地址
实体后来也需要
ZipCode
,那么您不需要添加3个ZipCode(1个用于家庭,1个用于商业,1个用于公司);您只需将
ZipCode
属性添加到
Address
类,而
Customer
类中的3个属性在不修改
Customer
类的情况下使用新属性。

阅读数据库规范化:谢谢!很好的解释。谢谢你让我知道什么是嵌套类。