简体   繁体   English

将一个类划分为子类

[英]Splitting up a class into sub-classes

I've got a business logic layer class containing access methods for each table in a database. 我有一个业务逻辑层类,其中包含数据库中每个表的访问方法。 As there are quite a few tables now I'd like to restructure it to group the methods by entity (for easier access when coding). 由于现在有很多表,我想对其进行重组,以按实体对方法进行分组(以便在编码时更易于访问)。 So, from this: 因此,从此:

BLL.Database MyDB = new BLL.Database();
BLL.Entity.User MyUser = Database.UserGetById(42);

to this: 对此:

BLL.Database MyDB = new BLL.Database();
BLL.Entity.User MyUser = Database.User.GetById(42);

I'd like the class to remain non-static if possible, with all the classes 'partial' too (to allow me to add additional methods to the main generated class). 我希望该类在可能的情况下保持非静态,而所有类也都是“部分”的(允许我向生成的主类中添加其他方法)。 What are my options for achieving this? 我有什么选择来实现这一目标? Here's the current layout: 这是当前的布局:

namespace BLL
{
    public partial class Database
    {
        // private members..
        // constructor

        #region User
        public IQueryable<BLL.Entity.User> UserGetAll()
        {
            // ...
        }

        public BLL.Entity.User UserGetById(int UserId)
        {
            // ...
        }

        public void UserSave(ref BLL.Entity.User user)
        {
            // ...
        }

        public void UserDelete(int userId)
        {
            // ...
        }
        #endregion

        // More sets of methods for other entities in database here..
    }
}

Is this feasible? 这可行吗?

namespace BLL
{
    public partial class Database
    {
        private _User;
        public User
        {
            if (_User == null)
            {
                _User = new User();
            }
            return _User;
        }

        // Other data access classes here..
    }

    public partial class User
    {
        public IQueryable<BLL.Entity.User> GetAll()
        {
            // ...
        }

        // GetById, Save & Delete methods here..
    }
}

Thanks. 谢谢。

Aside from the use of partial , your layout looks good. 除了使用partial ,您的布局看起来还不错。 I don't think partial is going to do the trick for you as far as making the classes extensible, as partial classes must all reside in the same assembly. 我不认为partial可以为您提供足够的扩展性,因为partial类必须全部驻留在同一程序集中。

A better solution would likely be creating extension methods . 更好的解决方案可能是创建扩展方法

Yes, that is feasible. 是的,那是可行的。 In fact I implemented something a lot like that. 实际上,我实现了很多类似的东西。

Of course, after doing so I heard about Linq to SQL and we started using that instead... so you might want to check that out as another option. 当然,这样做之后,我听说了有关SQL的Linq,我们开始使用它了……所以您可能希望将其检查为另一种选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM