Skip to main content
 首页 » 编程设计

c#之OOP 设计以及列表和集合 (C#)

2024年02月03日24虾米哥

我需要设计一个简单的软件,我想知道最好的做法。

首先,对于新手问题,抱歉:使用列表的最佳方式是什么?我尝试了几次,但没有意识到实例化它们的正确方法以及如何在 OOP 中使用它们。谁能帮我解决一下?

第二个问题是:我有以下类(格式松散,不是代码)

Tenement: 
tenementID Int32, 
polygons Polygon, (here i need to use a list, but how?) 
status TenementStatus; 
 
Polygon: 
polygonID Int32, 
vertexes vertex (need to use a list here too), 
areaPolygon; 
 
Vertex: 
vertexID Int32, 
X Int32, 
Y Int32; 

我对这些类(class)的看法是否正确?有更简单的方法吗?

请您参考如下方法:

在 C# 中,您需要使用 List<T>处理列表集合的类。

例如:

public class Tenement 
{ 
     public Tenement() 
     { 
         this.Polygons = new List<Polygon>(); // Create the list here... 
     } 
     public int Id { get; set; } 
     public IList<Polygon> Polygons { get; private set; } 
     // ... 

编辑: 如果您需要控制项目的添加或删除方式,例如检查以确保多边形有效,您还可以执行以下操作:

public class Tenement 
{ 
     public Tenement() 
     { 
         this.polygons = new List<Polygon>(); // Create the list here... 
     } 
     private List<Polygon> polygons; 
 
     public int Id { get; set; } 
     public IEnumerable<Polygon> Polygons {  
        get { return this.polygons; } 
     } 
     public void AddPolygon(Polygon polygon) { 
         // Do extra stuff here, then: 
         this.polygons.Add(polygon); 
     } 
     // ...