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

前端之家收集整理的这篇文章主要介绍了为什么在VB.NET中,当它在C#.NET中有效时,不能覆盖Interface ReadOnly属性?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
(这与 this other question有关)

如果你定义一个只有一个getter的接口的接口(= VBO中的ReadOnly),你为什么要在用C#实现类而不是用VB实现类时定义setter?

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

示例:对于此接口

'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:

06004

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要求实现接口成员以具有该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;
        }
    }
}

这确实给出了一个错误

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

猜你在找的VB相关文章