简体   繁体   中英

VB.net Overridable property not same as c# Virtual property?

Well its simple here you have my vb.net code:

Public Class Class1
    Public Overridable ReadOnly Property Name() As String
        Get
            Return Nothing
        End Get
    End Property
End Class

Public Class Class2
    Inherits Class1
    Public Overloads ReadOnly Property Name() As String
        Get
            Return "Class2"
        End Get
    End Property
End Class

Module Module1
    Sub Main()
        Dim c2 As New Class2()
        Console.WriteLine(c2.Name)
        Dim c1 As Class1 = CType(c2, Class1)
        Console.WriteLine(c1.Name)
    End Sub
End Module

And here comes the c# code:

class Class1
{
    public virtual string Name
    {
        get
        {
            return null;
        }
    }
}

class Class2 : Class1
{
    public override string Name
    {
        get
        {
            return "Class2";
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Class2 c2 = new Class2();
        Console.WriteLine(c2.Name);
        Class1 c1 = (Class1)c2;
        Console.WriteLine(c1.Name);
    }
}

i did expekt them to do the same thing but guess what thay dont! C# Output

Class2

Class2

VB.NET output

Class2

{Nothing}

(It dosent print nothing it just prints an empty line) Why does vb.net go for the base class implementation when its overriden?

它应该是重写而不是过载吗?

Public Overrides ReadOnly Property Name() As String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM