[英]why can't we have concrete implementation of base interface in aggregation?
在實現接口時,為什么不能在聚合中具體實現基本接口?
違反哪個OOP原則? StorageEntitySas
本質上是IStorageEntitySas類型
public interface IValetKeyResponse
{
IStorageEntitySas Sas { get; set; }
string UploadUrl { get; set; }
}
public class ValetKeyResponse : IValetKeyResponse
{
//Which OOP, principle is violating here? StorageEntitySas is essentially of type IStorageEntitySas
**public StorageEntitySas Sas { get; set; }**
public string UploadUrl { get; set; }
}
public class StorageEntitySas : IStorageEntitySas
{
public string Credentials { get; set; }
public Uri BlobUri { get; set; }
public string Name { get; set; }
}
接口定義了每個實現類都必須履行的契約 。 它定義了方法必須返回的內容以及可以使用的參數。 特別是,你的界面的用戶不知道-而不必知道具體的類,它是一個實現細節的東西。
但是,您仍然可以執行以下操作:
public class ValetKeyResponse : IValetKeyResponse
{
public IStorageEntitySas Sas { get; set; } = new StorageEntitySas();
public string UploadUrl { get; set; }
}
那么為什么不允許這樣做呢? 假設您有一個僅返回接口類型的API。
IValetKeyResponse response = myClass.GetValetResponse();
// what am I allowed to pass here when I don´t know the actual class of response?
response.Sas = ...
該API的客戶端不知道您實際上獲得了哪個類,因此不知道您被允許分配給該實例哪種IStorageEntitySaS
。 這就是合同所定義的內容,它表示您可以傳遞實現IStorageEntitySas
任何內容。
Sas
屬性上的setter允許您提供IStorageEntitySas
任何實現。 這意味着您應該能夠:
public class OtherStorageSas : IStorageEntitySas { ... }
IValetKeyResponse r = new ValetKeyResponse();
r.Sas = new OtherStorageSas();
如果允許的話,這將不是類型安全的,因為ValetKeyResponse.Sas
具有不兼容的類型StorageEntitySas
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.