gpt4 book ai didi

.net - 当接口(interface) ReadOnly 属性在 C#.NET 中有效时,为什么不能在 VB.NET 中覆盖它?

转载 作者:行者123 更新时间:2023-12-02 08:44:20 24 4
gpt4 key购买 nike

(这与 this other question 相关)

如果您定义一个接口(interface),其中有一个仅具有 getter 的属性(= VB.NET 中的 ReadOnly),为什么您可以在使用 C# 实现类时定义 setter,而不能使用 VB

我本以为它是在 .NET 级别定义的,而不是特定于语言的。

示例:对于此接口(interface)

'VB.NET
Interface SomeInterface

'the interface only say that implementers must provide a value for reading
ReadOnly Property PublicProperty As String

End Interface

//C# code
interface IPublicProperty
{
string PublicProperty { get; }
}

这是 C# 中的正确实现:

public class Implementer:IPublicProperty
{
private string _publicProperty;

public string PublicProperty
{
get
{
return _publicProperty;
}
set
{
_publicProperty = value;
}
}
}

但这在VB.NET中是无效的

Public Property PublicProperty As String Implements SomeInterface.PublicProperty
Get
Return _myProperty
End Get
Set(ByVal value As String)
_myProperty = value
End Set
End Property
<小时/>

更新2015/04/23

原来这个功能是作为 VB14 的一部分出现的!请参阅Languages features in C# 6 and VB 14New Language Features in Visual Basic 14 :

ReadOnly interface properties can be implemented by ReadWrite props This cleans up a quirky corner of the language. Look at this example:

Interface I
ReadOnly Property P As Integer
End Interface


Class C : Implements I
Public Property P As Integer Implements I.P
End Class

Previously, if you were implementing the ReadOnly property I.P, then you had to implement it with a ReadOnly property as well. Now that restriction has been relaxed: you can implement it with a read/write property if you want. This example happens to implement it with a read/write autoprop, but you can also use a property with getter and setter.

最佳答案

请小心假设 VB.NET 和 C# 是同一种语言,但口音不同 - 它们不是。

因为 VB.NET 要求接口(interface)成员的实现具有 Implements 子句,说明它正在实现哪个成员。 C# 允许您显式(类似于 VB.NET)或隐式(没有 VB.NET 等效项)实现接口(interface)成员。因此,实际 C# 版本是

public class Implementer : IPublicProperty
{
private string _publicProperty;

string IPublicProperty.PublicProperty // explicit implementation
{
get
{
return _publicProperty;
}
set
{
_publicProperty = value;
}
}
}

确实给出了一个错误:

error CS0550: 'ConsoleApplication171.Implementer.ConsoleApplication171.IPublicProperty.PublicProperty.set' adds an accessor not found in interface member 'ConsoleApplication171.IPublicProperty.PublicProperty'

关于.net - 当接口(interface) ReadOnly 属性在 C#.NET 中有效时,为什么不能在 VB.NET 中覆盖它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6341184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com