BindingFlags 열거형

정의

바인딩을 제어하는 플래그와 멤버 및 형식에 대한 검색이 리플렉션에 의해 수행되는 방식을 지정합니다.

이 열거형은 멤버 값의 비트 조합을 지원합니다.

public enum class BindingFlags
[System.Flags]
public enum BindingFlags
[System.Flags]
[System.Serializable]
public enum BindingFlags
[System.Flags]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum BindingFlags
[<System.Flags>]
type BindingFlags = 
[<System.Flags>]
[<System.Serializable>]
type BindingFlags = 
[<System.Flags>]
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type BindingFlags = 
Public Enum BindingFlags
상속
BindingFlags
특성

필드

Name Description
Default 0

바인딩 플래그가 정의되지 않음을 지정합니다.

IgnoreCase 1

바인딩할 때 멤버 이름의 대/소문자를 고려하지 않도록 지정합니다.

DeclaredOnly 2

제공된 형식의 계층 구조 수준에서 선언된 멤버만 고려되도록 지정합니다. 상속된 멤버는 고려되지 않습니다.

Instance 4

인스턴스 멤버를 검색에 포함하도록 지정합니다.

Static 8

정적 멤버를 검색에 포함하도록 지정합니다.

Public 16

공용 멤버를 검색에 포함하도록 지정합니다.

NonPublic 32

비공용 멤버를 검색에 포함하도록 지정합니다.

FlattenHierarchy 64

계층 구조의 퍼블릭 및 보호된 정적 멤버가 반환되도록 지정합니다. 상속된 클래스의 프라이빗 정적 멤버는 반환되지 않습니다. 정적 멤버에는 필드, 메서드, 이벤트 및 속성이 포함됩니다. 중첩된 형식은 반환되지 않습니다.

InvokeMethod 256

메서드를 호출하도록 지정합니다. 생성자 또는 형식 이니셜라이저가 아니어야 합니다.

이 플래그는 메서드를 InvokeMember 호출하는 메서드에 전달됩니다.

CreateInstance 512

리플렉션이 지정된 형식의 인스턴스를 만들 수 있도록 지정합니다. 지정된 인수와 일치하는 생성자를 호출합니다. 제공된 멤버 이름은 무시됩니다. 조회 형식이 지정되지 않은 경우(인스턴스 | 공용)이 적용됩니다. 형식 이니셜라이저를 호출할 수 없습니다.

이 플래그는 생성자를 호출하는 메서드에 전달 InvokeMember 됩니다.

GetField 1024

지정된 필드의 값이 반환되도록 지정합니다.

이 플래그는 필드 값을 가져오기 위해 InvokeMember 메서드에 전달됩니다.

SetField 2048

지정된 필드의 값을 설정하도록 지정합니다.

이 플래그는 필드 값을 설정하기 위해 InvokeMember 메서드에 전달됩니다.

GetProperty 4096

지정된 속성의 값이 반환되도록 지정합니다.

이 플래그는 속성 getter를 InvokeMember 호출하는 메서드에 전달됩니다.

SetProperty 8192

지정된 속성의 값을 설정하도록 지정합니다. COM 속성의 경우 이 바인딩 플래그를 지정하는 것은 지정 PutDispPropertyPutRefDispProperty동일합니다.

이 플래그는 속성 setter를 InvokeMember 호출하는 메서드에 전달됩니다.

PutDispProperty 16384

COM 개체의 PROPPUT 멤버를 호출할 것을 지정합니다. PROPPUT 는 값을 사용하는 속성 설정 함수를 지정합니다. 속성에 둘 다 PROPPUT 있고 PROPPUTREF 어떤 속성이 호출되는지 구분해야 하는 경우에 사용합니다PutDispProperty.

PutRefDispProperty 32768

COM 개체의 PROPPUTREF 멤버를 호출할 것을 지정합니다. PROPPUTREF 는 값 대신 참조를 사용하는 속성 설정 함수를 지정합니다. 속성에 둘 다 PROPPUT 있고 PROPPUTREF 어떤 속성이 호출되는지 구분해야 하는 경우에 사용합니다PutRefDispProperty.

ExactBinding 65536

제공된 인수의 형식이 해당 형식 매개 변수의 형식과 정확히 일치하도록 지정합니다. 호출자가 null Binder 이 아닌 개체를 제공하는 경우 호출자가 적절한 메서드를 선택할 구현을 제공하고 BindToXXX 있음을 의미하므로 리플렉션은 예외를 throw합니다. 기본 바인더는 이 플래그를 무시하고 사용자 지정 바인더는 이 플래그의 의미 체계를 구현할 수 있습니다.

SuppressChangeType 131072

구현되지 않았습니다.

OptionalParamBinding 262144

매개 변수 수가 제공된 인수 수와 일치하는 멤버 집합을 반환합니다. 이 바인딩 플래그는 기본값이 있는 매개 변수가 있는 메서드와 변수 인수(varargs)가 있는 메서드에 사용됩니다. 이 플래그는 .와 함께 InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])만 사용해야 합니다.

기본값이 있는 매개 변수는 후행 인수를 생략하는 호출에서만 사용됩니다. 마지막 인수여야 합니다.

IgnoreReturn 16777216

COM interop에서 멤버의 반환 값을 무시할 수 있도록 지정하는 데 사용됩니다.

DoNotWrapExceptions 33554432

예외를 에 래 TargetInvocationException핑하지 않도록 지정합니다.

예제

다음 예제에서는 많은 바인딩 플래그를 보여 줍니다.

using System;
using System.Reflection;
using System.IO;

namespace BindingFlagsSnippet
{
    class Example
    {
        static void Main()
        {
            // BindingFlags.InvokeMethod
            // Call a static method.
            Type t = typeof (TestClass);

            Console.WriteLine();
            Console.WriteLine("Invoking a static method.");
            Console.WriteLine("-------------------------");
            t.InvokeMember ("SayHello", BindingFlags.InvokeMethod | BindingFlags.Public |
                BindingFlags.Static, null, null, new object [] {});

            // BindingFlags.InvokeMethod
            // Call an instance method.
            TestClass c = new TestClass ();
            Console.WriteLine();
            Console.WriteLine("Invoking an instance method.");
            Console.WriteLine("----------------------------");
            c.GetType().InvokeMember ("AddUp", BindingFlags.InvokeMethod, null, c, new object [] {});
            c.GetType().InvokeMember ("AddUp", BindingFlags.InvokeMethod, null, c, new object [] {});

            // BindingFlags.InvokeMethod
            // Call a method with parameters.
            object [] args = new object [] {100.09, 184.45};
            object result;
            Console.WriteLine();
            Console.WriteLine("Invoking a method with parameters.");
            Console.WriteLine("---------------------------------");
            result = t.InvokeMember ("ComputeSum", BindingFlags.InvokeMethod, null, null, args);
            Console.WriteLine ("{0} + {1} = {2}", args[0], args[1], result);

            // BindingFlags.GetField, SetField
            Console.WriteLine();
            Console.WriteLine("Invoking a field (getting and setting.)");
            Console.WriteLine("--------------------------------------");
            // Get a field value.
            result = t.InvokeMember ("Name", BindingFlags.GetField, null, c, new object [] {});
            Console.WriteLine ("Name == {0}", result);
            // Set a field.
            t.InvokeMember ("Name", BindingFlags.SetField, null, c, new object [] {"NewName"});
            result = t.InvokeMember ("Name", BindingFlags.GetField, null, c, new object [] {});
            Console.WriteLine ("Name == {0}", result);

            Console.WriteLine();
            Console.WriteLine("Invoking an indexed property (getting and setting.)");
            Console.WriteLine("--------------------------------------------------");
            // BindingFlags.GetProperty
            // Get an indexed property value.
            int  index = 3;
            result = t.InvokeMember ("Item", BindingFlags.GetProperty, null, c, new object [] {index});
            Console.WriteLine ("Item[{0}] == {1}", index, result);
            // BindingFlags.SetProperty
            // Set an indexed property value.
            index = 3;
            t.InvokeMember ("Item", BindingFlags.SetProperty, null, c, new object [] {index, "NewValue"});
            result = t.InvokeMember ("Item", BindingFlags.GetProperty , null, c, new object [] {index});
            Console.WriteLine ("Item[{0}] == {1}", index, result);

            Console.WriteLine();
            Console.WriteLine("Getting a field or property.");
            Console.WriteLine("----------------------------");
            // BindingFlags.GetField
            // Get a field or property.
            result = t.InvokeMember ("Name", BindingFlags.GetField | BindingFlags.GetProperty, null, c,
                new object [] {});
            Console.WriteLine ("Name == {0}", result);
            // BindingFlags.GetProperty
            result = t.InvokeMember ("Value", BindingFlags.GetField | BindingFlags.GetProperty, null, c,
                new object [] {});
            Console.WriteLine ("Value == {0}", result);

            Console.WriteLine();
            Console.WriteLine("Invoking a method with named parameters.");
            Console.WriteLine("---------------------------------------");
            // BindingFlags.InvokeMethod
            // Call a method using named parameters.
            object[] argValues = new object [] {"Mouse", "Micky"};
            String [] argNames = new String [] {"lastName", "firstName"};
            t.InvokeMember ("PrintName", BindingFlags.InvokeMethod, null, null, argValues, null, null,
                argNames);

            Console.WriteLine();
            Console.WriteLine("Invoking a default member of a type.");
            Console.WriteLine("------------------------------------");
            // BindingFlags.Default
            // Call the default member of a type.
            Type t3 = typeof (TestClass2);
            t3.InvokeMember ("", BindingFlags.InvokeMethod | BindingFlags.Default, null, new TestClass2(),
                new object [] {});

            // BindingFlags.Static, NonPublic, and Public
            // Invoking a member with ref parameters.
            Console.WriteLine();
            Console.WriteLine("Invoking a method with ref parameters.");
            Console.WriteLine("--------------------------------------");
            MethodInfo m = t.GetMethod("Swap");
            args = new object[2];
            args[0] = 1;
            args[1] = 2;
            m.Invoke(new TestClass(),args);
            Console.WriteLine ("{0}, {1}", args[0], args[1]);

            // BindingFlags.CreateInstance
            // Creating an instance with a parameterless constructor.
            Console.WriteLine();
            Console.WriteLine("Creating an instance with a parameterless constructor.");
            Console.WriteLine("------------------------------------------------------");
            object cobj = t.InvokeMember ("TestClass", BindingFlags.Public |
                BindingFlags.Instance | BindingFlags.CreateInstance,
                null, null, new object [] {});
            Console.WriteLine("Instance of {0} created.", cobj.GetType().Name);

            // Creating an instance with a constructor that has parameters.
            Console.WriteLine();
            Console.WriteLine("Creating an instance with a constructor that has parameters.");
            Console.WriteLine("------------------------------------------------------------");
            cobj = t.InvokeMember ("TestClass", BindingFlags.Public |
                BindingFlags.Instance | BindingFlags.CreateInstance,
                null, null, new object [] { "Hello, World!" });
            Console.WriteLine("Instance of {0} created with initial value '{1}'.", cobj.GetType().Name,
                cobj.GetType().InvokeMember("Name", BindingFlags.GetField, null, cobj, null));

            // BindingFlags.DeclaredOnly
            Console.WriteLine();
            Console.WriteLine("DeclaredOnly instance members.");
            Console.WriteLine("------------------------------");
            System.Reflection.MemberInfo[] memInfo =
                t.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance |
                BindingFlags.Public);
            for(int i=0;i<memInfo.Length;i++)
            {
                Console.WriteLine(memInfo[i].Name);
            }

            // BindingFlags.IgnoreCase
            Console.WriteLine();
            Console.WriteLine("Using IgnoreCase and invoking the PrintName method.");
            Console.WriteLine("---------------------------------------------------");
            t.InvokeMember("printname", BindingFlags.IgnoreCase | BindingFlags.Static |
                BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new object[]
                {"Brad","Smith"});

            // BindingFlags.FlattenHierarchy
            Console.WriteLine();
            Console.WriteLine("Using FlattenHierarchy to get inherited static protected and public members." );
            Console.WriteLine("----------------------------------------------------------------------------");
            FieldInfo[] finfos = typeof(MostDerived).GetFields(BindingFlags.NonPublic | BindingFlags.Public |
                  BindingFlags.Static | BindingFlags.FlattenHierarchy);
            foreach (FieldInfo finfo in finfos)
            {
                Console.WriteLine("{0} defined in {1}.", finfo.Name, finfo.DeclaringType.Name);
            }

            Console.WriteLine();
            Console.WriteLine("Without FlattenHierarchy." );
            Console.WriteLine("-------------------------");
            finfos = typeof(MostDerived).GetFields(BindingFlags.NonPublic | BindingFlags.Public |
                  BindingFlags.Static);
            foreach (FieldInfo finfo in finfos)
            {
                Console.WriteLine("{0} defined in {1}.", finfo.Name, finfo.DeclaringType.Name);
            }
        }
    }

    public class TestClass
    {
        public String Name;
        private Object [] values = new Object [] {0, 1,2,3,4,5,6,7,8,9};

        public Object this [int index]
        {
            get
            {
                return values[index];
            }
            set
            {
                values[index] = value;
            }
        }

        public Object Value
        {
            get
            {
                return "the value";
            }
        }

        public TestClass () : this("initialName") {}
        public TestClass (string initName)
        {
            Name = initName;
        }

        int methodCalled = 0;

        public static void SayHello ()
        {
            Console.WriteLine ("Hello");
        }

        public void AddUp ()
        {
            methodCalled++;
            Console.WriteLine ("AddUp Called {0} times", methodCalled);
        }

        public static double ComputeSum (double d1, double d2)
        {
            return d1 + d2;
        }

        public static void PrintName (String firstName, String lastName)
        {
            Console.WriteLine ("{0},{1}", lastName,firstName);
        }

        public void PrintTime ()
        {
            Console.WriteLine (DateTime.Now);
        }

        public void Swap(ref int a, ref int b)
        {
            int x = a;
            a = b;
            b = x;
        }
    }

    [DefaultMemberAttribute ("PrintTime")]
    public class TestClass2
    {
        public void PrintTime ()
        {
            Console.WriteLine (DateTime.Now);
        }
    }

    public class Base
    {
        static int BaseOnlyPrivate = 0;
        protected static int BaseOnly = 0;
    }
    public class Derived : Base
    {
        public static int DerivedOnly = 0;
    }
    public class MostDerived : Derived {}
}

/* This example produces output similar to the following:

Invoking a static method.
-------------------------
Hello

Invoking an instance method.
----------------------------
AddUp Called 1 times
AddUp Called 2 times

Invoking a method with parameters.
---------------------------------
100.09 + 184.45 = 284.54

Invoking a field (getting and setting.)
--------------------------------------
Name == initialName
Name == NewName

Invoking an indexed property (getting and setting.)
--------------------------------------------------
Item[3] == 3
Item[3] == NewValue

Getting a field or property.
----------------------------
Name == NewName
Value == the value

Invoking a method with named parameters.
---------------------------------------
Mouse,Micky

Invoking a default member of a type.
------------------------------------
12/23/2009 4:29:21 PM

Invoking a method with ref parameters.
--------------------------------------
2, 1

Creating an instance with a parameterless constructor.
------------------------------------------------------
Instance of TestClass created.

Creating an instance with a constructor that has parameters.
------------------------------------------------------------
Instance of TestClass created with initial value 'Hello, World!'.

DeclaredOnly instance members.
------------------------------
get_Item
set_Item
get_Value
AddUp
PrintTime
Swap
.ctor
.ctor
Item
Value
Name

Using IgnoreCase and invoking the PrintName method.
---------------------------------------------------
Smith,Brad

Using FlattenHierarchy to get inherited static protected and public members.
----------------------------------------------------------------------------
DerivedOnly defined in Derived.
BaseOnly defined in Base.

Without FlattenHierarchy.
-------------------------

 */
Imports System.Reflection
Imports System.IO

Class Invoke

    Public Shared Sub Main()
        ' BindingFlags.InvokeMethod
        ' Call a static method.
        Dim t As Type = GetType(TestClass)

        Console.WriteLine()
        Console.WriteLine("Invoking a static method.")
        Console.WriteLine("-------------------------")
        t.InvokeMember("SayHello", BindingFlags.InvokeMethod Or BindingFlags.Public _
            Or BindingFlags.Static, Nothing, Nothing, New Object() {})

        ' BindingFlags.InvokeMethod
        ' Call an instance method.
        Dim c As New TestClass()
        Console.WriteLine()
        Console.WriteLine("Invoking an instance method.")
        Console.WriteLine("----------------------------")
        c.GetType().InvokeMember("AddUp", BindingFlags.InvokeMethod, Nothing, c, New Object() {})
        c.GetType().InvokeMember("AddUp", BindingFlags.InvokeMethod, Nothing, c, New Object() {})

        ' BindingFlags.InvokeMethod
        ' Call a method with parameters.
        Dim args() As Object = {100.09, 184.45}
        Dim result As Object
        Console.WriteLine()
        Console.WriteLine("Invoking a method with parameters.")
        Console.WriteLine("---------------------------------")
        result = t.InvokeMember("ComputeSum", BindingFlags.InvokeMethod, Nothing, Nothing, args)
        Console.WriteLine("{0} + {1} = {2}", args(0), args(1), result)

        ' BindingFlags.GetField, SetField
        Console.WriteLine()
        Console.WriteLine("Invoking a field (getting and setting.)")
        Console.WriteLine("--------------------------------------")
        ' Get a field value.
        result = t.InvokeMember("Name", BindingFlags.GetField, Nothing, c, New Object() {})
        Console.WriteLine("Name == {0}", result)
        ' Set a field.
        t.InvokeMember("Name", BindingFlags.SetField, Nothing, c, New Object() {"NewName"})
        result = t.InvokeMember("Name", BindingFlags.GetField, Nothing, c, New Object() {})
        Console.WriteLine("Name == {0}", result)

        Console.WriteLine()
        Console.WriteLine("Invoking an indexed property (getting and setting.)")
        Console.WriteLine("--------------------------------------------------")
        ' BindingFlags.GetProperty 
        ' Get an indexed property value.
        Dim index As Integer = 3
        result = t.InvokeMember("Item", BindingFlags.GetProperty, Nothing, c, New Object() {index})
        Console.WriteLine("Item[{0}] == {1}", index, result)
        ' BindingFlags.SetProperty
        ' Set an indexed property value.
        index = 3
        t.InvokeMember("Item", BindingFlags.SetProperty, Nothing, c, New Object() {index, "NewValue"})
        result = t.InvokeMember("Item", BindingFlags.GetProperty, Nothing, c, New Object() {index})
        Console.WriteLine("Item[{0}] == {1}", index, result)

        Console.WriteLine()
        Console.WriteLine("Getting a field or property.")
        Console.WriteLine("----------------------------")
        ' BindingFlags.GetField
        ' Get a field or property.
        result = t.InvokeMember("Name", BindingFlags.GetField Or BindingFlags.GetProperty, Nothing, _
            c, New Object() {})
        Console.WriteLine("Name == {0}", result)
        ' BindingFlags.GetProperty
        result = t.InvokeMember("Value", BindingFlags.GetField Or BindingFlags.GetProperty, Nothing, _
            c, New Object() {})
        Console.WriteLine("Value == {0}", result)

        Console.WriteLine()
        Console.WriteLine("Invoking a method with named parameters.")
        Console.WriteLine("---------------------------------------")
        ' BindingFlags.InvokeMethod
        ' Call a method using named parameters.
        Dim argValues() As Object = {"Mouse", "Micky"}
        Dim argNames() As [String] = {"lastName", "firstName"}
        t.InvokeMember("PrintName", BindingFlags.InvokeMethod, Nothing, Nothing, argValues, Nothing, _
            Nothing, argNames)

        Console.WriteLine()
        Console.WriteLine("Invoking a default member of a type.")
        Console.WriteLine("------------------------------------")
        ' BindingFlags.Default
        ' Call the default member of a type.
        Dim t3 As Type = GetType(TestClass2)
        t3.InvokeMember("", BindingFlags.InvokeMethod Or BindingFlags.Default, Nothing, _
            New TestClass2(), New Object() {})

        Console.WriteLine()
        Console.WriteLine("Invoking a method with ByRef parameters.")
        Console.WriteLine("----------------------------------------")
        ' BindingFlags.Static, NonPublic, and Public
        ' Invoking a member by reference.
        Dim m As MethodInfo = t.GetMethod("Swap")
        args = New Object(1) {}
        args(0) = 1
        args(1) = 2
        m.Invoke(New TestClass(), args)
        Console.WriteLine("{0}, {1}", args(0), args(1))

        ' BindingFlags.CreateInstance
        ' Creating an instance.
        Console.WriteLine()
        Console.WriteLine("Creating an instance with parameterless constructor.")
        Console.WriteLine("----------------------------------------------------")
        Dim obj As Object = GetType(TestClass).InvokeMember("TestClass", BindingFlags.CreateInstance, _
            Nothing, Nothing, New Object() {})
        Console.WriteLine("Instance of {0} created.", obj.GetType().Name)

        Console.WriteLine()
        Console.WriteLine("Creating an instance with a constructor that has parameters.")
        Console.WriteLine("------------------------------------------------------------")
        obj = GetType(TestClass).InvokeMember("TestClass", BindingFlags.CreateInstance, Nothing, _
            Nothing, New Object() { "Hello, World!" })
        Console.WriteLine("Instance of {0} created with initial value '{1}'.", obj.GetType().Name, _
            obj.GetType().InvokeMember("Name", BindingFlags.GetField, Nothing, obj, Nothing))

        ' BindingFlags.DeclaredOnly
        Console.WriteLine()
        Console.WriteLine("DeclaredOnly instance members.")
        Console.WriteLine("------------------------------")
        Dim memInfo As System.Reflection.MemberInfo() = t.GetMembers(BindingFlags.DeclaredOnly Or _
            BindingFlags.Public Or BindingFlags.Instance)
        Dim i As Integer
        For i = 0 To memInfo.Length - 1
            Console.WriteLine(memInfo(i).Name)
        Next i

        ' BindingFlags.IgnoreCase
        Console.WriteLine()
        Console.WriteLine("Using IgnoreCase and invoking the PrintName method.")
        Console.WriteLine("---------------------------------------------------")
        t.InvokeMember("printname", BindingFlags.IgnoreCase Or BindingFlags.Public Or _
            BindingFlags.Static Or BindingFlags.InvokeMethod, Nothing, Nothing, _
            New Object() {"Brad", "Smith"})

        ' BindingFlags.FlattenHierarchy
        Console.WriteLine()
        Console.WriteLine("Using FlattenHierarchy to get inherited static protected and public members." )
        Console.WriteLine("----------------------------------------------------------------------------")
        Dim finfos() As FieldInfo = GetType(MostDerived).GetFields(BindingFlags.NonPublic Or _
              BindingFlags.Public Or BindingFlags.Static Or BindingFlags.FlattenHierarchy)
        For Each finfo As FieldInfo In finfos
            Console.WriteLine("{0} defined in {1}.", finfo.Name, finfo.DeclaringType.Name)
        Next

        Console.WriteLine()
        Console.WriteLine("Without FlattenHierarchy." )
        Console.WriteLine("-------------------------")
        finfos = GetType(MostDerived).GetFields(BindingFlags.NonPublic Or BindingFlags.Public Or _
              BindingFlags.Static)
        For Each finfo As FieldInfo In finfos
            Console.WriteLine("{0} defined in {1}.", finfo.Name, finfo.DeclaringType.Name)
        Next
    End Sub
End Class

Public Class TestClass
    Public Name As String
    Private values() As [Object] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

    Default Public Property Item(ByVal index As Integer) As [Object]
        Get
            Return values(index)
        End Get
        Set(ByVal Value As [Object])
            values(index) = Value
        End Set
    End Property

    Public ReadOnly Property Value() As [Object]
        Get
            Return "the value"
        End Get
    End Property

    Public Sub New(ByVal initName As String)
        Name = initName
    End Sub 

    Public Sub New()
        MyClass.New("initialName")
    End Sub 

    Private methodCalled As Integer = 0

    Public Shared Sub SayHello()
        Console.WriteLine("Hello")
    End Sub 

    Public Sub AddUp()
        methodCalled += 1
        Console.WriteLine("AddUp Called {0} times", methodCalled)
    End Sub 

    Public Shared Function ComputeSum(ByVal d1 As Double, ByVal d2 As Double) As Double
        Return d1 + d2
    End Function 

    Public Shared Sub PrintName(ByVal firstName As [String], ByVal lastName As [String])
        Console.WriteLine("{0},{1}", lastName, firstName)
    End Sub 

    Public Sub PrintTime()
        Console.WriteLine(DateTime.Now)
    End Sub 

    Public Sub Swap(ByRef a As Integer, ByRef b As Integer)
        Dim x As Integer = a
        a = b
        b = x
    End Sub
End Class

<DefaultMemberAttribute("PrintTime")> _
Public Class TestClass2

    Public Sub PrintTime()
        Console.WriteLine(DateTime.Now)
    End Sub 
End Class

Public Class Base
    Shared BaseOnlyPrivate As Integer = 0
    Protected Shared BaseOnly As Integer = 0
End Class

Public Class Derived 
    Inherits Base
    Public Shared DerivedOnly As Integer = 0
End Class

Public Class MostDerived 
    Inherits Derived
End Class

' This example produces output similar to the following:
'
'Invoking a static method.
'-------------------------
'Hello
'
'Invoking an instance method.
'----------------------------
'AddUp Called 1 times
'AddUp Called 2 times
'
'Invoking a method with parameters.
'---------------------------------
'100.09 + 184.45 = 284.54
'
'Invoking a field (getting and setting.)
'--------------------------------------
'Name == initialName
'Name == NewName
'
'Invoking an indexed property (getting and setting.)
'--------------------------------------------------
'Item[3] == 3
'Item[3] == NewValue
'
'Getting a field or property.
'----------------------------
'Name == NewName
'Value == the value
'
'Invoking a method with named parameters.
'---------------------------------------
'Mouse,Micky
'
'Invoking a default member of a type.
'------------------------------------
'12/23/2009 4:34:22 PM
'
'Invoking a method with ByRef parameters.
'----------------------------------------
'2, 1
'
'Creating an instance with parameterless constructor.
'----------------------------------------------------
'Instance of TestClass created.
'
'Creating an instance with a constructor that has parameters.
'------------------------------------------------------------
'Instance of TestClass created with initial value 'Hello, World!'.
'
'DeclaredOnly instance members.
'------------------------------
'get_Item
'set_Item
'get_Value
'AddUp
'PrintTime
'Swap
'.ctor
'.ctor
'Item
'Value
'Name
'
'Using IgnoreCase and invoking the PrintName method.
'---------------------------------------------------
'Smith,Brad
'
'Using FlattenHierarchy to get inherited static protected and public members.
'----------------------------------------------------------------------------
'DerivedOnly defined in Derived.
'BaseOnly defined in Base.
'
'Without FlattenHierarchy.
'-------------------------
'

설명

이러한 BindingFlags 컨트롤 바인딩은 멤버 및 형식을 호출, 만들기, 가져오기, 설정 및 System.Runtime 찾는 네임스페이스의 많은 클래스 SystemSystem.Reflection및 네임스페이스에 대한 바인딩입니다.

BindingFlags는 다음과 같은 Type 메서드 및 기타 위치에서 사용됩니다.MethodBase.Invoke

InvokeMember 특히 중요합니다 GetMethod .

바인딩 플래그는 다음 표에 나열된 대로 형식 멤버를 식별하는 방법에 따라 분류할 수 있습니다.

접근성으로 식별됨 바인딩 인수로 식별됨 작업으로 식별됨
DeclaredOnly

FlattenHierarchy

IgnoreCase

IgnoreReturn

Instance

비공개

공용

정적
ExactBinding

OptionalParamBinding
인스턴스 생성

GetField

SetField

GetProperty

SetProperty

메소드 호출

PutDispProperty

PutRefDispProperty

메모

멤버를 Public 지정 Instance 하거나 Static 함께 반환 NonPublic 하거나 반환하지 않아야 합니다.

다음 표에서는 기본적으로 Binder.ChangeType수행되는 강제 변환을 나열합니다. 이 테이블은 바인딩 플래그에 BindingFlags.ExactBinding 특히 적용됩니다. 일반적인 원칙은 ChangeType 데이터를 잃지 않는 확대 강제 변환만 수행해야 한다는 것입니다. 확대 강제 변환의 예는 부속된 32비트 정수 값을 64비트 부가 정수 값으로 강제 변환하는 것입니다. 이는 데이터가 손실될 수 있는 축소된 강제 변환과 구별됩니다. 축소된 강제 변환의 예로 64비트 부가 정수는 부가된 32비트 정수로 강제 변환합니다.

원본 형식 대상 유형
모든 형식 기본 형식입니다.
모든 형식 구현하는 인터페이스입니다.
Char UInt16, UInt32, Int32, UInt64, Int64, SingleDouble
Byte Char,UInt16, Int16, UInt32, Int32, UInt64Int64, SingleDouble
SByte Int16, Int32, Int64, SingleDouble
UInt16 UInt32, Int32, UInt64, Int64, SingleDouble
Int16 Int32, Int64, , Single, Double
UInt32 UInt64, Int64, , Single, Double
Int32 Int64, , SingleDouble
UInt64 Single, Double
Int64 Single, Double
Single Double
비 참조 참조 기준입니다.

바인딩 플래그를 BindingFlags.ExactBinding 사용하는 경우 리플렉션은 공통 형식 시스템의 접근성 규칙을 모델화합니다. 예를 들어 호출자가 동일한 어셈블리에 있는 경우 호출자는 내부 멤버에 대한 특별한 권한이 필요하지 않습니다. 그렇지 않으면 호출자가 필요합니다 ReflectionPermission. 이는 보호되는 멤버, 프라이빗 등의 멤버 조회와 일치합니다.

적용 대상