簡體   English   中英

陰影(VB.NET)和新(C#)之間的區別

[英]Difference between Shadows (VB.NET) and New (C#)

簡單的問題來自一個簡單的問題:VB.NET中的Shadows關鍵字和C#中的New關鍵字有什么區別? (關於方法簽名當然)。

它們完全相同。 Shadows是C#的new關鍵字的VB.NET等價物。 它們在語義上意味着相同的東西,並且它們編譯成相同的IL。

在某些版本的Visual Studio中(我不確定是否仍然如此),在VB.NET項目中使用Shadows關鍵字可以隱藏Intellisense中具有相同名稱的所有函數。 但這實際上並不是一種語言特征; 它甚至不清楚是設計還是實施Intellisense的錯誤。 如果您使用來自C#應用程序的相同VB.NET庫,您將看到所有方法,就好像它們是用new聲明的一樣。

它們完全相同。

C#中不存在Shadowing概念

考慮一個帶有一些重載的vb.net基類:

Public Class BaseClass
    Public Function SomeMethod() As String
        Return String.Empty
    End Function
    Public Function SomeMethod(SomeParam As String) As String
        Return "Base from String"
    End Function

    Public Function SomeMethod(SomeParam As Integer) As String
        Return "Base from Integer"
    End Function
    Public Function SomeMethod(SomeParamB As Boolean) As String
        Return "Base from Boolean"
    End Function
End Class

而這個派生類:

Public Class DerivedClass
    Inherits BaseClass

    Public Shadows Function SomeMethod(SomeParam As String) As String
        Return "Derived from String"
    End Function
End Class

現在考慮實施:

Dim DerivedInstance = New DerivedClass()

DerivedInstance只有一個版本的SomeMethod, 所有其他基本版本都被遮蔽了

如果你在C#項目中編譯和引用程序集,你可以看到會發生什么:

DerivedInstance陰影方法

要在VB.Net中執行隱藏 ,您仍然必須使用重載 (或者如果基本方法被標記為 覆蓋,覆蓋 )關鍵字:

Public Class DerivedClass
    Inherits BaseClass

    Public Overloads Function SomeMethod(SomeParam As String) As String
        Return "Derived from String"
    End Function
End Class

這是編譯后發生的事情:

DerivedInstance隱藏方法

所以,在VB.Net中,如果你在一個與基類相匹配的簽名上使用了重載關鍵字,你就會隱藏那個基本版本的方法,就像在c#中一樣:

public class DerivedClass : BaseClass
{
    public new string SomeMethod(string someParam)
    {
        return "Derived from String";
    }
}

編輯:這是IL代碼:

來自C#:

.method public hidebysig specialname rtspecialname instance void .ctor () cil managed 
{
    IL_0000: ldarg.0
    IL_0001: call instance void Shadowing_CS.BaseClass::.ctor()
    IL_0006: ret
}

.method public hidebysig instance string SomeMethod (
        string s
    ) cil managed 
{
    IL_0000: ldstr "Derived from string"
    IL_0005: ret
}

來自VB:

.method public specialname rtspecialname instance void .ctor () cil managed 
{
    IL_0000: ldarg.0
    IL_0001: call instance void Shadowing_VB.BaseClass::.ctor()
    IL_0006: ret
}

.method public instance string SomeMethod (
        string s
    ) cil managed 
{
    IL_0000: ldstr "Derived from string"
    IL_0005: ret
}

所以....他們並不完全相同。

注意:在downvote之前......請....嘗試。

它們是相同的,它只是實現相同OOP概念的語言特定關鍵字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM