0

我正在尝试对一个Connection对象进行子类化以创建一个AuthenticatedConnection,它应该以与 a 相同的方式运行Connection,并添加一个标记。一个直接的解决方案是通过“包装”与子类构造函数的连接。

该解决方案似乎已损坏,因为我无法访问参数的受保护成员。这意味着不能调用基本构造函数。有没有办法实现构造函数,以便可以像这样包装构造函数?例如:new AuthenticatedConnection("token", existingConnection)

这是当前(损坏的)实现。编译错误是:Cannot access protected member 'Connection._client' via a qualifier of type 'Connection'; the qualifier must be of type 'AuthenticatedConnection' (or derived from it)

class Connection
{
    // internal details of the connection; should not be public.
    protected object _client;

    // base class constructor
    public Connection(object client) { _client = client; }
}

class AuthenticatedConnection : Connection
{
    // broken constructor?
    public AuthenticatedConnection(string token, Connection connection)
        : base(connection._client)
    {
        // use token etc
    }
}
4

2 回答 2

5

最简单的解决方案是为基类创建一个“复制构造函数”:

class Connection
{
    // internal details of the connection; should not be public.
    protected object _client;

    // base class constructor
    public Connection(object client) { _client = client; }

    // copying constructor
    public Connection(Connection other) : this(other._client) { }
}

class AuthenticatedConnection : Connection
{
    // broken constructor?
    public AuthenticatedConnection(string token, Connection connection)
        : base(connection)
    {
        // use token etc
    }
}
于 2013-06-08T10:56:03.590 回答
0

一个直接的解决方案是通过“包装”与子类构造函数的连接

这并不简单,IMO。直截了当是这样的:

class AuthenticatedConnection : Connection
{
    public AuthenticatedConnection1(string token, object client)
        : base(client)
    {
        // use token etc
    }
}

但如果你想包装真正的连接,我会这样做:

interface IConnection {}
class Connection : IConnection
{
    // internal details of the connection; should not be public.
    protected object _client;

    // base class constructor
    public Connection(object client) { _client = client; }
}

class AuthenticatedConnection : IConnection
{
    private readonly IConnection connection;

    public AuthenticatedConnection2(string token, IConnection connection)
    {
        // use token etc
    }
}
于 2013-06-08T11:16:57.880 回答