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

问题描述

| (这与此其他问题有关) 如果您定义一个接口,在该接口中只有一个getter的属性(在VB.NET中为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的一部分! 请参见C#6和VB 14中的语言功能以及Visual Basic 14中的新语言功能:   ReadWly道具可以实现ReadOnly接口属性   这清除了该语言的一个古怪的角落。看这个例子:
Interface I
    ReadOnly Property P As Integer
End Interface


Class C : Implements I
    Public Property P As Integer Implements I.P
End Class
     以前,如果要实现ReadOnly属性I.P,则   您还必须使用ReadOnly属性来实现它。现在   限制已经放松:您可以通过读/写实现   属性,如果你想。这个例子恰好是用   读/写autoprop,但是您也可以将属性与getter和   二传手。     

解决方法

        请注意,假设VB.NET和C#是同一种语言,但口音不同,但不是。 因为VB.NET要求接口成员的实现具有该
Implements
子句,说明它正在实现哪个成员。 C#使您可以显式(类似于VB.NET)或隐式(无VB.NET等效)实现接口成员。因此,实际的C#版本是
public class Implementer : IPublicProperty
{
    private string _publicProperty;

    string IPublicProperty.PublicProperty    // explicit implementation
    {
        get
        {
            return _publicProperty;
        }
        set
        {
            _publicProperty = value;
        }
    }
}
这确实给出了一个错误:   错误CS0550:\'ConsoleApplication171.Implementer.ConsoleApplication171.IPublicProperty.PublicProperty.set \'添加了在接口成员\'ConsoleApplication171.IPublicProperty.PublicProperty \中找不到的访问器     ,        在.net中,接口中只读属性的实现必须包含getter但不包含setter,并且读写属性的实现必须同时包含getter和setter。对于只写属性(如果定义了这样的事情)的实现,还必须包括一个setter但不包含getter。 在C#中,如果类定义了与接口中的属性同名的公共属性,该公共属性实现该接口所需的方法,并且该类未显式实现接口属性,则编译器将自动生成一个属性视情况使用公共财产的获取器和/或设置器。即使一个类实现了三个接口,一个具有只读属性
Foo
,一个具有只读属性
Foo
,一个具有读写属性
Foo
,也可以使用单个公共读写属性
Foo
来实现该接口。所有人都拥有“ 7”财产。 从概念上讲,没有理由vb.net无法提供类似的功能,并且会根据实现接口的需要生成两个(甚至三个)不同的属性。至少目前,如果将vb.net类成员标记为实现接口成员,则期望它会与该成员完美匹配而不进行包装。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...