C# - 我应该使用什么,接口、抽象类还是两者?

Car*_*l J 5 .net c# abstract-class interface

因此,假设我正在用 C# 构建某种房地产应用程序。对于每种类型的财产,我将创建一个类,例如 ResidentialProperty 和 CommercialProperty。这两个类以及所有其他属性类将共享一些公共属性,例如 Id、标题、描述和地址信息。

我希望能够做的是:
a)返回仅包含基本信息的对象集合
b)能够调用诸如GetProperty(id)之类的方法,该方法将创建并返回ResidentialProperty或CommercialProperty,或者调用 GetProperties() ,它将返回其中之一或两者的集合。

因此,创建一个名为 BasicProperty(或 PropertyBase)的抽象类可能是有意义的,它包含所有公共属性,并从它扩展 ResidentialProperty 和 CommercialProperty。这将解决问题 #1,因为我可以创建一个返回 BasicProperties 集合的方法。

但对于#2,能够返回一种属性类型或另一种属性类型,我需要一个接口(IProperty),并让住宅和商业类继承它,然后让 GetProperty(id) 和 GetProperties() 返回IProperty 对象(或者因为它们继承自 IProperty,我可以按原样返回它们而不是作为接口吗?)?

现在,如果我应该使用接口,我该如何处理 BasicProperty 类?
- 我是否将其保留为抽象并实现接口?或者
- 我是否将其保留为抽象并且所有 3 个类都实现该接口?或者
-我不将其创建为抽象,将所有基本信息放入接口中,并且BasicProperty、ResidentialProperty和CommercialProperty都实现该接口吗?

提前致谢,卡尔·J.

Mar*_*ark 1

据我所知,你在这里谈论的是两件不同的事情。

  1. 类结构
  2. 这些类的数据访问

您认为应该创建一个抽象类来包含公共属性,这是正确的,这就是继承的用途:)(除其他外)

但我不明白为什么你不能创建一个数据访问类,该类具有GetProperty(id)指定返回类型的方法PropertyBase

IE

public PropertyBase GetProperty(long id)

在实现中,GetProperty您可以构造一个ResidentialPropertyor CommercialProperty(基于您想要的业务/数据库逻辑)然后返回它,C# 允许您这样做。

或许是我没理解你的意思?

华泰

编辑::

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    class DataAccessLayer
    {
        public PropertyBase GetSomething(int id)
        {
            if (id > 10)
                return new CommercialProperty();
            else
                return new ResidentialProperty();
        }

    }

    class PropertyBase { }
    class ResidentialProperty : PropertyBase { } 
    class CommercialProperty : PropertyBase { }
}
Run Code Online (Sandbox Code Playgroud)