簡體   English   中英

在子類構造函數中復制受保護的字段

[英]Copy protected field in subclass constructor

我正在嘗試對Connection對象進行子類化,以創建AuthenticatedConnection ,它應該與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) 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
    }
}

最簡單的解決方案是為基類創建一個“復制構造函數”:

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
    }
}

一個簡單的解決方案是通過子類構造函數傳遞“包裝”連接

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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM