[英]How to have C# interface with readonly member
我最近發現自己需要一些東西,這在 C# 中應該是非常可能的(我知道它在 C++ 中):幾個類需要一個 api 密鑰,它絕對必須是一個私有的、不可變的字段(除了在構造函數)。 為了避免代碼重復,我想為需要 api 密鑰的類創建一個接口。
我會讓代碼不言自明:
public interface IHasApiKey
{
protected readonly string _apiKey = String.Empty;
}
問題:
readonly
的行為。 (const,但可以在構造函數中設置)System.ComponentModel.ReadOnlyAttribute
,但文檔非常有限,它看起來不像readonly
那樣執行,而更像是可以在用戶代碼中查詢的屬性。為了完整起見,這里是我想象的正確代碼在 C++ 中的樣子:
class IHasApiKey
{
private:
std::string _apiKey = "";
protected:
IHasApiKey(const std::string& apiKey) : _apiKey(apiKey) {}
// tbo, I'm not quite sure about how to optimally write this one,
// but the idea is the same: provide protected read access.
const std::string& GetKey() { return const_cast<std::string&>(_apiKey); }
};
我解釋得對嗎? 有沒有人知道如何優雅地解決這個問題? 非常感謝。
C# 接口沒有狀態,您不能在接口不可寫非只讀中聲明字段。 事實證明,為了保持狀態,您需要類,因此在您的情況下,它應該是基類或具體類...
一種方法是在接口中聲明一個 get 屬性,這將強制實現該接口的所有類提供 get
public interface IHasApiKey
{
string ApiKey {get;}
}
和類應該是這樣的
public class SomeFoo : IHasApiKey
{
private readonly string _apiKey;
public SomeFoo(string apiKey)
{
_apiKey = apiKey;
}
public string ApiKey => _apiKey;
}
看來我受語言選擇的限制。 C# 沒有辦法完成我想要的。 最好的辦法是允許裝飾界面的 setter:
public interface IHasApiKey
{
protected string _apiKey { get; readonly set; }
}
但這可能需要對編譯器進行不可能的更改,並且可能會破壞語言設計。 我發現它不太可能被添加。
感謝所有花時間考慮這個問題的人!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.