【发布时间】:2021-04-14 21:43:03
【问题描述】:
我指的是微软的文档 - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties 。他们指出,当 get 或 set 中不需要额外的逻辑时,自动实现的属性基本上是没有主体的属性。所以int Myproperty1 {get;set;} 是一个自动实现的属性。本文档还说明了以下几点
声明1: “您不能在接口中声明自动实现的属性。自动实现的属性声明私有实例支持字段,并且接口可能不声明实例字段。”
但我可以在接口中声明如下自动实现的属性
public MyInterface { int Myproperty1 {get;set;} 。这与我们不能在接口中声明自动实现的属性的声明不冲突吗?
Microsoft 文档然后说: 声明2: “在不定义主体的情况下在接口中声明属性会声明具有访问器的属性,该访问器必须由实现该接口的每种类型实现。”
我不明白什么是声明没有 body 的属性,它不是自动实现的属性,如果是,那么第一条语句不正确吗?
对问题的重要编辑: 抱歉,我错误地使用此链接发布了问题: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-properties。 虽然我打算参考以下链接: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties。我现在用正确的链接更新了我的问题。
【问题讨论】:
-
所有自动属性都没有实体,但并非所有没有实体的属性都是自动属性。这两种说法都不是错误的。
-
Is this not conflicting above statement that we cant declare auto implemented properties in Interface.不,不是。在您意识到相同的{ get; set; }语法在接口与类中意味着不同的事物之前,它可能会混淆。在接口中,它的意思是“实现类需要实现这个”(即"Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.")。在类中,它表示“自动实现的属性”(带有私有实例支持字段)。 -
But i can declare auto implemented property like below in an interface不,你不能。 看起来(对你来说)就像一个汽车属性。但它不是(根据定义——因为接口不能有自动属性)。
标签: c# properties