为什么在VB.NET中,当它在C#.NET中有效时,不能覆盖Interface ReadOnly属性?

tsi*_*lar 9 .net c#-to-vb.net vb.net-to-c#

(这与其他问题有关)

如果你定义一个接口,其中有一个属性,只有一个getter(=只读在VB.NET),为什么你能在实施与C#类定义的制定者而不是用VB

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

示例:对于此接口

'VB.NET
Interface SomeInterface

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

End Interface
Run Code Online (Sandbox Code Playgroud)

要么

//C# code
interface IPublicProperty
{
    string PublicProperty { get; }
}
Run Code Online (Sandbox Code Playgroud)

这是C#中的正确实现:

public class Implementer:IPublicProperty
    {
        private string _publicProperty;

        public string PublicProperty
        {
            get
            {
                return _publicProperty;
            }
            set
            {
                _publicProperty = value;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但这在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
Run Code Online (Sandbox Code Playgroud)

更新2015/04/23

事实证明这个功能是VB14的一部分!见一些语言特点在C#6和VB 14新的语言功能在Visual Basic 14:

ReadOnly接口属性可以通过ReadWrite道具实现这可以清除语言的一个古怪角落.看看这个例子:

Interface I
    ReadOnly Property P As Integer
End Interface


Class C : Implements I
    Public Property P As Integer Implements I.P
End Class
Run Code Online (Sandbox Code Playgroud)

以前,如果您正在实现ReadOnly属性IP,那么您还必须使用ReadOnly属性来实现它.现在已经放宽了限制:如果需要,可以使用读/写属性实现它.此示例恰好使用读/写autoprop实现它,但您也可以使用带getter和setter的属性.

Aak*_*shM 11

请注意,假设VB.NET和C#是使用不同口音的同一种语言 - 它们不是.

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

public class Implementer : IPublicProperty
{
    private string _publicProperty;

    string IPublicProperty.PublicProperty    // explicit implementation
    {
        get
        {
            return _publicProperty;
        }
        set
        {
            _publicProperty = value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

确实给出了一个错误:

错误CS0550:'ConsoleApplication171.Implementer.ConsoleApplication171.IPublicProperty.PublicProperty.set'添加了在接口成员'ConsoleApplication171.IPublicProperty.PublicProperty'中找不到的访问者

  • 真正让我烦恼的是,最后,一个属性只是一个访问器,据我记忆,编译器最终在MSIL中生成某种访问器方法,如"myProp_Set","my_Prop_Get",因此定义一个setter只会在实施者中导致"添加一个额外的方法",这不是我所说的打破界面...但我在这里说的可能是完全错误的......我对这个过程发生的知识非常有限从"高级"语言到MSIL ...... (2认同)