Поделиться через


MethodBase.IsHideBySig Свойство

Определение

Возвращает значение, указывающее, скрывается ли в производном классе только член такого же вида с точно такой же сигнатурой.

public:
 property bool IsHideBySig { bool get(); };
public bool IsHideBySig { get; }
member this.IsHideBySig : bool
Public ReadOnly Property IsHideBySig As Boolean

Значение свойства

Значение true, если член скрыт на основе сигнатуры; в обратном случае — значение false.

Реализации

Примеры

Следующий пример кода содержит базовый класс с перегруженным методом и производный класс, скрывающий одну из перегрузок. В версии Visual Basic примера IsHideBySig кода свойство возвращает false для члена в производном классе. В версии C# примера кода свойство возвращает true для члена в производном классе.

using System;
using System.Reflection;

// The base class B contains an overloaded method M.
//
public class B
{
    public virtual void M()
    {
        Console.WriteLine("B's M()");
    }
    public virtual void M(int x)
    {
        Console.WriteLine("B's M({0})", x);
    }
}

// The derived class D hides one overload of the inherited 
// method M.
//
public class D:
    B
{
    new public void M(int i)
    {
        Console.WriteLine("D's M({0})", i);
    }
}

public class Test
{
    public static void Main()
    {
        D dinst = new D();
        // In C#, the method in the derived class hides by name and by
        // signature, so the overload in the derived class hides only one
        // of the overloads in the base class.
        //
        Console.WriteLine("------ List the overloads of M in the derived class D ------");
        Type t = dinst.GetType();
        foreach( MethodInfo minfo in t.GetMethods() )
        {
            if (minfo.Name=="M") {Console.WriteLine("Overload of M: {0}  IsHideBySig = {1}, DeclaringType = {2}", minfo, minfo.IsHideBySig, minfo.DeclaringType);}
        }

        // The method M in the derived class hides one overload of the 
        // method in B.  Contrast this with Visual Basic, which hides by
        // name instead of by name and signature.  In Visual Basic, the
        // parameterless overload of M would be unavailable from D.
        //
        Console.WriteLine("------ Call the overloads of M available in D ------");
        dinst.M();
        dinst.M(42);
        
        // If D is cast to the base type B, both overloads of the 
        // shadowed method can be called.
        //
        Console.WriteLine("------ Call the shadowed overloads of M ------");
        B binst = dinst;
        binst.M();
        binst.M(42);
    } //Main
} //Test

/* This code example produces the following output:

------ List the overloads of M in the derived class D ------
Overload of M: Void M(Int32)  IsHideBySig = True, DeclaringType = B
Overload of M: Void M()  IsHideBySig = True, DeclaringType = B
Overload of M: Void M(Int32)  IsHideBySig = True, DeclaringType = D
------ Call the overloads of M available in D ------
B's M()
D's M(42)
------ Call the shadowed overloads of M ------
B's M()
B's M(42)
*/
Imports System.Reflection

' The base class B contains an overloaded method M.
'
Public Class B
    Public Overridable Sub M()
        Console.WriteLine("B's M()")
    End Sub
    Public Overridable Sub M(ByVal x As Integer)
        Console.WriteLine("B's M({0})", x)
    End Sub
End Class

' The derived class D hides the inherited method M.
'
Public Class D
    Inherits B
    Shadows Public Sub M(ByVal i As Integer)
        Console.WriteLine("D's M({0})", i)
    End Sub
End Class

Public Class Test
    Public Shared Sub Main()
        Dim dinst As New D()
        ' In Visual Basic, the method in the derived class hides by
        ' name, rather than by signature.  Thus, although a list of all the 
        ' overloads of M shows three overloads, only one can be called from
        ' class D.  
        '
        Console.WriteLine("------ List the overloads of M in the derived class D ------")
        Dim t As Type = dinst.GetType()
        For Each minfo As MethodInfo In t.GetMethods()
            If minfo.Name = "M" Then Console.WriteLine( _
                "Overload of M: {0}  IsHideBySig = {1}, DeclaringType = {2}", _
                minfo, minfo.IsHideBySig, minfo.DeclaringType)
        Next

        ' The method M in the derived class hides the method in B.
        '
        Console.WriteLine("------ Call the overloads of M available in D ------")
        ' The following line causes a compile error, because both overloads
        ' in the base class are hidden.  Contrast this with C#, where only 
        ' one of the overloads of B would be hidden.
        'dinst.M()
        dinst.M(42)
        
        ' If D is cast to the base type B, both overloads of the 
        ' shadowed method can be called.
        '
        Console.WriteLine("------ Call the shadowed overloads of M ------")
        Dim binst As B = dinst
        binst.M()
        binst.M(42)         
    End Sub
End Class

' This code example produces the following output:
' ------ List the overloads of M in the derived class D ------
' Overload of M: Void M(Int32)  IsHideBySig = False, DeclaringType = B
' Overload of M: Void M()  IsHideBySig = False, DeclaringType = B
' Overload of M: Void M(Int32)  IsHideBySig = False, DeclaringType = D
' ------ Call the overloads of M available in D ------
' D's M(42)
' ------ Call the shadowed overloads of M ------
' B's M()
' B's M(42)

Комментарии

Когда член в производном классе объявляется с помощью модификатора C# new или модификатора Visual Basic Shadows , он может скрыть член с таким же именем в базовом классе. C# скрывает члены базового класса с помощью сигнатуры. То есть, если член базового класса имеет несколько перегрузок, единственным скрытым является тот, который имеет идентичную сигнатуру. В отличие от этого, Visual Basic скрывает все перегрузки базового класса. Таким образом, возвращается false для элемента, IsHideBySig объявленного модификатором Visual BasicShadows, и true для элемента, объявленного модификатором C#new.

Предупреждение

Это свойство не определяет, имеет NewSlot ли метод атрибут . Метод, объявленный модификатором newShadows или , будет иметь NewSlot атрибут , но только методы, объявленные с new (т. е. только методы C#), будут иметь IsHideBySig свойство , равное true. Чтобы определить, имеет NewSlot ли метод атрибут , используйте код, аналогичный следующему: if ((myMethodInfo.Attributes & MethodAttributes.VtableLayoutMask) == MethodAttributes.NewSlot) в C# или If (myMethodInfo.Attributes And MethodAttributes.VtableLayoutMask) = MethodAttributes.NewSlot в Visual Basic. Однако обратите внимание, что, хотя все методы, объявленные с атрибутом NewSlot или Shadows , не все методы, имеющие NewSlot атрибут , объявляются с new или Shadows.new

Применяется к