Why can't Interface ReadOnly properties be overridden in VB.NET, when it is valid in C#.NET?

空扰寡人 提交于 2019-12-01 16:11:41

Be careful assuming that VB.NET and C# are the same language spoken with a different accent - they're not.

Because VB.NET requires implementation of an interface member to have that Implements clause, saying which member it is implementing. C# lets you implement interface members explicitly (SORT OF like VB.NET), or implicitly (no VB.NET equivalent). Therefore the actual C# version of this is

public class Implementer : IPublicProperty
{
    private string _publicProperty;

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

and this does gives an error:

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

In .net, it is necessary that an implementation of a read-only property in an interface include a getter but no setter, and for the implementation of a read-write property to include both a getter and a setter. It is also necessary for the implementation of a write-only property (if one defines such a thing) to include a setter but no getter.

In C#, if a class defines a public property with the same name as a property in an interface, the public property implements the methods required by that interface, and the class does not explicitly implement the interface property, the compiler will automatically generate a property which uses the getter and/or setter of the public property, as appropriate. Even if a class implements three interfaces, one with a read-only property Foo, one with a write-only property Foo, and one with a read-write property Foo, a single public read-write property Foo can be used to implement the Foo property for all of them.

Conceptually, there's no reason vb.net couldn't offer a similar feature, and generate two (or even three) different properties as required to implement interfaces. At least at present, if a vb.net class member is marked as implementing an interface member, the expectation is that it will match the member perfectly without wrapping.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!