Access to classes

本文关键字:classes to Access | 更新日期: 2023-09-27 18:07:33

我不确定在哪里/如何搜索这个问题,所以我想问stackoverflow社区是最好的选择。

基本上我正在设计一个项目,它将简单地提供一个逻辑项目访问一个LINQ到SQL模型来执行数据库上的CRUD。因此,在Data项目中,我有LINQ to SQL模型类和c#类来提供对模型的访问,如下所示

public class Connection : IDisposable
{
    private DataModelDataContext _model;
    public DataModelDataContext model
    {
        get { return _model; }
        set { throw new Exception("Object '"model'" is not allowed to be created outside of its container class", new NotSupportedException()); }
    }
    public Connection(string username, string password)
    {
        User u = _model.Users.Where(u => u.Username == username && u.password == u.Password);
        if (u == null)
            throw new ApplicationException("User credentials are invalid", new AuthenticationException());
        _model = new DataModelDataContext();
    }
    public void refreshAndKeepChanges(object entity)
    {
        _model.Refresh(RefreshMode.OverwriteCurrentValues, entity);
    }
    public int getChangesCount()
    {
        return _model.GetChangeSet().Deletes.Count() + _model.GetChangeSet().Inserts.Count() + _model.GetChangeSet().Updates.Count();
    }
    public void Dispose()
    {
        _model.SubmitChanges();
        _model.Dispose();
    }
}

我想要的是,当我编译DLL时,逻辑项目可以访问Connection类(上面),但不能访问DataModelDataContext(因为这会破坏传递用户凭据的对象)。

我的问题是如何暴露连接类(作为我已经做过的公共),但从DLL中隐藏LINQ到SQL数据模型,但允许连接类访问它?

使用额外的命名空间为LINQ到SQL模型不起作用,我发现添加DLL允许访问项目内的所有命名空间。

Access to classes

只需将model属性更改为内部属性,以及DataModelDataContext类(这可能通过编辑DBML来完成,无论是在设计器中还是手工)。Connection类知道内部类是可以的——只是不能公开地暴露它们。

作为一对题外话:

  • 如果model setter永远不会起作用,为什么要有它呢?把它处理掉。
  • 你应该开始遵循。net命名约定

public DataModelDataContext model更改为

internal DataModelDataContext model

如果您希望它在该程序集中是公共的,但对所有其他程序集中是私有的

protected DataModelDataContext model

private DataModelDataContext model

如果您不想将DataModelDataContext暴露给该程序集中的其他类。

很可能你想把它改成internal

您可以搜索(或直接在MSDN上阅读更多)的术语是访问修饰符。