复制子类构造函数中的受保护字段

时间:2013-06-08 10:47:58

标签: c# inheritance

我正在尝试子类化Connection对象以创建AuthenticatedConnection,它应该以与Connection相同的方式运行,并添加一个令牌。一个简单的解决方案是使用子类构造函数传递'wrap'连接。

此解决方案似乎已损坏,因为我无法访问参数的受保护成员。这意味着无法调用基础构造函数。有没有办法实现构造函数,以便可以像这样包装构造函数? 例如: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
    }
}

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:0)

  

一个简单的解决方案是使用子类构造函数

传递'wrap'连接

这不是直截了当的,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
    }
}
相关问题