0

我见过一些这样的例子:

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; } 
}

有什么想法吗?

干杯。

4

2 回答 2

2

Your class is not nested, it just uses composition. Composition is composing a class from one or more other classes. It's advantage is reuse of course.

You can use your Address class in another class or method and you also encapsulate all the logic and data that must be in the Address class.

If you want nested classes then you can write it as:

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

    public class Worm
    {
         public string Name;
    }
}
于 2013-09-02T11:16:49.027 回答
0

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

您的示例中的主要优点是,它Address是一个单独的实体(已重构),并且可用于指示给定地址的不同分类,Customer例如,客户可能具有 a Home Address、 aBusiness Address和 a Corporate Address,它们都将属于类型Address类。

否则,在没有单独的类的情况下实现上述类型的分类Address将很困难,这Address就是将其作为单独的类取出的一个原因。

作为说明,您的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; }
}

现在,根据上面的示例,如果您的Address实体稍后ZipCode也需要,那么您不需要添加 3 个邮政编码(1 个用于家庭,1 个用于商业,1 个用于公司);您只需将ZipCode属性添加到Address类中,类中的 3 个属性即可使用Customer新属性而无需修改Customer类。

于 2013-09-02T11:28:01.413 回答