如何在.net中创建几个零到一个或一个关系的类

时间:2012-08-25 20:35:31

标签: .net oop

我是.net和OOP的新手,我一直在努力解决如何为我正在建设的地产网站创建课程。

在我的数据库中,我有一个包含各种字段的“House”表。

有时候,房子可能有花园,车库,游泳池等,所以我有单独的表来存储每一个的数据,所有这些都连接到“House”表的唯一标识符。

在我的代码中,我创建了一个“House”类,但是如何为其他表定义类呢?

我显然可以有一个“花园”课程,它将继承“众议院”课程,但是,根据访客的选择,我有时可能需要在(例如)房子,花园和车库上显示数据我看不出这种方法是如何工作的。我可以只有一个大班来定义房子,花园,车库等等,并在不需要的时候留下很多空值,但我很确定这不是正确的做法!

我一整天都在苦苦挣扎,所以非常感谢任何信息!

1 个答案:

答案 0 :(得分:3)

House类可能有一系列功能。

您可以基本创建一个名为“Feature”的抽象基类或一个名为“IFeature”的接口,并将其继承/实现到要作为特征的类(即Garden)。

然后您需要做的就是在House类中创建一个名为“Features”的集合 这是C#中的示例界面:

interface IFeature
{
    // Properties or methods you want all the features to have.

    decimal Price { get; }
}

您的要素类需要实现IFeature界面。

class Garden : IFeature
{
    // This property is needed to implement IFeature interface.
    public decimal Price { get; private set; }

    public Garden(decimal price) { Price = price; }
}

要实施IFeature,一个类必须有一个名为“Price”的decimal属性,并带有一个get访问器,如上面的Garden类和下面的Pool类:< / p>

class Pool : IFeature
{
    public decimal Price { get; private set; }
    public float Depth { get; private set; }

    public Pool(decimal price, float depth) { Price = price; Depth = depth; }
}

House类应该包含IFeature而不是PoolGarden的集合:

class House
{
    public List<IFeature> Features { get; private set; }

    public House()
    {
        Features = new List<IFeature>();
    }
}

然后,您可以像这样向房子添加功能:

House h = new House();

h.Features.Add(new Garden(6248.12m));
h.Features.Add(new Pool(4830.24m, 10.4f));

使用LINQ,你可以,

// Check whether the house has a garden:
h.Features.Any(f => f is Garden);

// Get the total cost of features.
h.Features.Sum(f => f.Price);

// Get the pools that are deeper than 5 feet.
h.Features.OfType<Pool>().Where(p => p.Depth > 5f);

// etc.

More information about interfaces
More information about LINQ