![](/img/trans.png)
[英]C#: Internal and public interfaces, auto-implemented properties, but with structs…
[英]Auto implemented Properties in C# Interfaces
我指的是 Microsoft 的文檔 - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties 。 他們 state 認為自動實現的屬性基本上是沒有主體的屬性,當在 get 或 set 中不需要額外的邏輯時。 所以int Myproperty1 {get;set;}
是一個自動實現的屬性。 本文檔還說明了以下幾點
聲明 1: “您不能在接口中聲明自動實現的屬性。自動實現的屬性聲明私有實例支持字段,並且接口可能不聲明實例字段。”
但我可以在接口中聲明如下自動實現的屬性
public MyInterface { int Myproperty1 {get;set;}
。 這與我們不能在接口中聲明自動實現的屬性的上述聲明不沖突嗎?
微軟文檔接着說: statement2: “在接口中聲明一個屬性而不定義一個主體聲明了一個帶有訪問器的屬性,該訪問器必須由實現該接口的每種類型實現。”
我不明白什么是聲明沒有正文的屬性,它不是自動實現的屬性,如果是,那么第一條語句不正確嗎?
對問題的重要編輯:抱歉,我錯誤地使用此鏈接發布了問題: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-屬性。 雖然我打算參考以下鏈接: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties 。 我現在用正確的鏈接更新了我的問題。
MSDN 從未說過“所有沒有實體的屬性都是自動實現的屬性”。 他們可能會說“自動實現的屬性沒有實體”,但后者並不意味着前者。 MSDN 並不自相矛盾。
接口中沒有主體的屬性是abstract
的,而自動實現的屬性是非抽象的、沒有主體的並且在類/結構中的屬性。
因此, public MyInterface { int MyProperty1
public MyInterface { int MyProperty1 {get;set;} }
中的 MyProperty1 不是自動實現的屬性,而是抽象的。
我不明白什么是聲明沒有正文的財產
這就像在接口中聲明兩個沒有主體的方法:
public MyInterfaceWithTwoMethods {
int GetMyProperty1();
void SetMyProperty1(int value);
}
除了在 C# 中使用屬性更慣用。
您可以使用自動實現的屬性來實現MyInterface
:
public class MyImpl : MyInterface {
public int MyProperty1 { get; set; }
}
即使您似乎只是在重復MyInterface
中所寫的內容,這也類似於像這樣實現MyInterfaceWithTwoMethods
:
public class MyImpl : MyInterfaceWithTwoMethods {
private int myProperty1;
int GetMyProperty1() => myProperty1;
void SetMyProperty1(int value) { myProperty1 = value; }
}
您也可以不使用自動實現的屬性來實現MyInterface
:
public class MyImpl : MyInterface {
public int MyProperty1 {
get => 1;
set { Console.WriteLine("foo"); }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.