加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-17 00:17:44 所属栏目:大数据 来源:网络整理
导读:(这与 this other question有关) 如果你定义一个只有一个getter的接口的接口(= VBO中的ReadOnly),你为什么要在用C#实现类而不是用VB实现类时定义setter? 我原以为它是在.NET级别定义的,而不是特定于语言的. 示例:对于此接口 'VB.NETInterface SomeInterfac
(这与 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 14和New 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’

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读