[英]Difference between Shadows (VB.NET) and New (C#)
簡單的問題來自一個簡單的問題:VB.NET中的Shadows
關鍵字和C#中的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#項目中編譯和引用程序集,你可以看到會發生什么:
要在VB.Net中執行隱藏 ,您仍然必須使用重載 (或者如果基本方法被標記為可 覆蓋,則覆蓋 )關鍵字:
Public Class DerivedClass
Inherits BaseClass
Public Overloads Function SomeMethod(SomeParam As String) As String
Return "Derived from String"
End Function
End Class
這是編譯后發生的事情:
所以,在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.