다음을 통해 공유


BindingFlags 열거형

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

이 열거형에는 멤버 값를 비트로 조합할 수 있는 FlagsAttribute 특성이 있습니다.

네임스페이스: System.Reflection
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
<FlagsAttribute> _
Public Enumeration BindingFlags
‘사용 방법
Dim instance As BindingFlags
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
[FlagsAttribute] 
public enum BindingFlags
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
[FlagsAttribute] 
public enum class BindingFlags
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute FlagsAttribute() */ 
public enum BindingFlags
SerializableAttribute 
ComVisibleAttribute(true) 
FlagsAttribute 
public enum BindingFlags

멤버

  멤버 이름 설명
Supported by the .NET Compact Framework CreateInstance 리플렉션에서 지정된 형식의 인스턴스를 만들도록 지정합니다. 주어진 인수에 해당하는 생성자를 호출합니다. 지정된 멤버 이름은 무시됩니다. 조회 형식이 지정되지 않은 경우 (인스턴스 | 형식 이니셜라이저는 호출할 수 없습니다. 
Supported by the .NET Compact Framework DeclaredOnly 지정된 형식의 계층 구조 수준으로 선언된 멤버만 고려되도록 지정합니다. 상속된 멤버는 고려되지 않습니다. 
Supported by the .NET Compact Framework Default 바인딩 플래그를 지정하지 않습니다. 
Supported by the .NET Compact Framework ExactBinding 지정된 인수의 형식이 대응하는 형식 매개 변수의 형식과 정확하게 일치하도록 지정합니다. 리플렉션에서는 호출자가 null이 아닌 Binder 개체를 제공하면 적합한 메서드를 선택하는 BindToXXX 구현을 제공하는 것이므로 예외를 throw합니다. 

리플렉션은 공용 형식 시스템의 액세스 가능성 규칙을 모델링합니다. 예를 들어, 같은 어셈블리에 있는 호출자는 내부 멤버에 대해 특별한 권한이 필요하지 않습니다. 그렇지 않은 경우에는 호출자에 ReflectionPermission이 있어야 합니다. 이는 보호된 멤버, 전용 멤버 등을 조회할 때도 마찬가지입니다.

일반적인 원칙은 ChangeType에서 데이터 손실이 없는 확장 강제 변환을 수행해야 한다는 것입니다. 확장 강제 변환의 예로는 32비트 부호 있는 정수 값을 64비트 부호 있는 정수 값으로 변환하는 것을 들 수 있습니다. 확장 강제 변환은 데이터가 손상될 수 있는 축소 변환과 구분됩니다. 축소 변환의 예로는 64비트 부호 있는 정수를 32비트 부호 있는 정수로 변환하는 것을 들 수 있습니다.

기본 바인더는 이 플래그를 무시하지만 사용자 지정 바인더는 이 플래그의 의미를 구현할 수 있습니다.

Supported by the .NET Compact Framework FlattenHierarchy 계층 구조 위쪽의 공용 및 보호되는 정적 멤버가 반환되도록 지정합니다. 상속된 클래스의 전용 정적 멤버는 반환되지 않습니다. 정적 멤버에는 필드, 메서드, 이벤트, 속성이 있습니다. 중첩된 형식은 반환되지 않습니다. 
Supported by the .NET Compact Framework GetField 지정된 필드의 값이 반환되도록 지정합니다. 
Supported by the .NET Compact Framework GetProperty 지정된 속성의 값이 반환되도록 지정합니다. 
Supported by the .NET Compact Framework IgnoreCase 바인딩할 때 멤버 이름의 대/소문자를 구분하지 않도록 지정합니다. 
Supported by the .NET Compact Framework IgnoreReturn COM interop에서 사용되어 멤버의 반환 값을 무시할 수 있도록 지정합니다. 
Supported by the .NET Compact Framework Instance 인스턴스 멤버를 검색에 포함시키도록 지정합니다. 
Supported by the .NET Compact Framework InvokeMethod 메서드를 불러오도록 지정합니다. 이는 생성자 또는 형식 이니셜라이저가 될 수 없습니다. 
Supported by the .NET Compact Framework NonPublic 비공용 멤버를 검색에 포함시키도록 지정합니다. 
Supported by the .NET Compact Framework OptionalParamBinding 매개 변수 개수가 지정된 인수의 개수와 일치하는 멤버 집합을 반환합니다. 이 바인딩 플래그는 기본값을 사용하는 매개 변수가 있는 메서드와 가변 인수(varargs)가 있는 메서드에 사용됩니다. 이 플래그는 Type.InvokeMember을 통해 사용해야만 합니다. 

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

Supported by the .NET Compact Framework Public 공용 멤버를 검색에 포함시키도록 지정합니다. 
Supported by the .NET Compact Framework PutDispProperty COM 개체의 PROPPUT 멤버를 불러오도록 지정합니다. PROPPUT은 값을 사용하는 속성 설정 함수를 지정합니다. 속성에 PROPPUTPROPPUTREF가 모두 있고 이 중에서 호출할 대상을 선택해야 하는 경우 PutDispProperty를 사용합니다. 
Supported by the .NET Compact Framework PutRefDispProperty COM 개체의 PROPPUTREF 멤버를 불러오도록 지정합니다. PROPPUTREF는 값 대신 참조를 사용하는 속성 설정 함수를 지정합니다. 속성에 PROPPUTPROPPUTREF가 모두 있고 이 중에서 호출할 대상을 선택해야 하는 경우 PutRefDispProperty를 사용합니다. 
Supported by the .NET Compact Framework SetField 지정된 필드의 값을 설정하도록 지정합니다. 
Supported by the .NET Compact Framework SetProperty 지정된 속성의 값을 설정하도록 지정합니다. COM 속성의 경우 이 바인딩 플래그를 지정하는 것은 PutDispPropertyPutRefDispProperty를 지정하는 것과 같습니다. 
Supported by the .NET Compact Framework Static 정적 멤버를 검색에 포함시키도록 지정합니다. 
Supported by the .NET Compact Framework SuppressChangeType 구현되지 않았습니다. 

설명

이러한 BindingFlags는 멤버 및 형식을 불러오고 만들고 가져오고 설정하고 검색하는 System, System.ReflectionSystem.Runtime 네임스페이스에 있는 많은 클래스에 대한 바인딩을 제어합니다.

BindingFlags는 다음과 같은 Type 메서드와 MethodBase.Invoke 등에서 사용합니다.

InvokeMemberGetMethod는 특히 중요합니다.

다음 표에서 보여 주는 것처럼 형식 멤버를 식별하는 방식에 따라 바인딩 플래그를 분류할 수 있습니다.

액세스 가능성으로 식별

바인딩 인수로 식별

작업으로 식별

DeclaredOnly

FlattenHierarchy

IgnoreCase

IgnoreReturn

Instance

NonPublic

Public

Static

ExactBinding

OptionalParamBinding

CreateInstance

GetField

SetField

GetProperty

SetProperty

InvokeMethod

PutDispProperty

PutRefDispProperty

참고

Instance 또는 StaticPublic 또는 NonPublic과 함께 지정해야 합니다. 그렇지 않으면 멤버가 반환되지 않습니다.

다음 표에는 기본 Binder.ChangeType에서 수행된 변환이 나열되어 있습니다. 이 표는 특히 ExactBinding 바인딩 플래그에 적용됩니다.

소스 형식

대상 형식

모든 형식

기본 형식

모든 형식

해당 형식이 구현하는 인터페이스입니다.

Char

UInt16, UInt32, Int32, UInt64, Int64, Single, Double

Byte

Char, UInt16, Int16, UInt32, Int32, UInt64, Int64, Single, Double

SByte

Int16, Int32, Int64, Single, Double

UInt16

UInt32, Int32, UInt64, Int64, Single, Double

Int16

Int32, Int64, Single, Double

UInt32

UInt64, Int64, Single, Double

Int32

Int64, Single, Double

UInt64

Single, Double

Int64

Single, Double

Single

Double

비참조 형식

참조 형식

예제

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

Imports System
Imports System.Reflection
Imports System.IO

Class EntryPoint
    Overloads Shared Sub Main(ByVal args() As String)
        Invoke.Go()
    End Sub 'Main
End Class 'EntryPoint



Class Invoke

    Public Shared Sub Go()
        ' 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, 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 by reference.")
        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))
        ' The string is case-sensitive.
        Dim type As Type = type.GetType("System.String")

        ' Check to see if the value is valid. If the object is null, the type does not exist.
        If type Is Nothing Then
            Console.WriteLine("Please ensure that you specify only valid types in the type field.")
            Console.WriteLine("The type name is case-sensitive.")
            Return
        End If
        ' Declare and populate the arrays to hold the information.
        ' You must declare either NonPublic or Public with Static or the search will not work.
        Dim fi As FieldInfo() = type.GetFields((BindingFlags.Static Or BindingFlags.NonPublic Or BindingFlags.Public))
        ' BindingFlags.NonPublic 
        Dim miNonPublic As MethodInfo() = type.GetMethods((BindingFlags.Static Or BindingFlags.NonPublic))
        ' BindingFlags.Public
        Dim miPublic As MethodInfo() = type.GetMethods((BindingFlags.Static Or BindingFlags.Public))

        ' Iterate through all the nonpublic methods.
        Dim method As MethodInfo
        For Each method In miNonPublic
            Console.WriteLine(method)
        Next method
        ' Iterate through all the public methods.
        For Each method In miPublic
            Console.WriteLine(method)
        Next method
        ' Iterate through all the fields.
        Dim f As FieldInfo
        For Each f In fi
            Console.WriteLine(f)
        Next f

        ' Call an instance method.
        Dim tc As New TestClass()
        Console.WriteLine()
        Console.WriteLine("Invoking an Instance method.")
        Console.WriteLine("----------------------------")
        tc.GetType().InvokeMember("AddUp", BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.CreateInstance, Nothing, tc, New Object() {})

        ' BindingFlags.CreateInstance
        ' Calling and creating an instance method.
        Console.WriteLine()
        Console.WriteLine("Invoking and creating an instance method.")
        Console.WriteLine("-----------------------------------------")
        tc.GetType().InvokeMember("AddUp", BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.CreateInstance, Nothing, tc, New Object() {})

        ' BindingFlags.DeclaredOnly
        Dim tc2 As New TestClass()
        Console.WriteLine()
        Console.WriteLine("DeclaredOnly members")
        Console.WriteLine("---------------------------------")
        Dim memInfo As System.Reflection.MemberInfo() = tc2.GetType().GetMembers(BindingFlags.DeclaredOnly)
        Dim i As Integer
        For i = 0 To memInfo.Length - 1
            Console.WriteLine(memInfo(i).Name)
        Next i

        ' BindingFlags.SuppressChangeType
        Dim obj As New TestClass()
        Console.WriteLine()
        Console.WriteLine("Invoking static method - PrintName")
        Console.WriteLine("---------------------------------")
        Dim methInfo As System.Reflection.MethodInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.SuppressChangeType Or BindingFlags.InvokeMethod, Nothing, New Object() {"Brad", "Smith"}, Nothing)

        ' BindingFlags.IgnoreCase
        Console.WriteLine()
        Console.WriteLine("Using IgnoreCase and invoking the PrintName method.")
        Console.WriteLine("---------------------------------------------------")
        methInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.IgnoreCase Or BindingFlags.InvokeMethod, Nothing, New Object() {"brad", "smith"}, Nothing)

        ' BindingFlags.IgnoreReturn
        Console.WriteLine()
        Console.WriteLine("Using IgnoreReturn and invoking the PrintName method.")
        Console.WriteLine("-----------------------------------------------------")
        methInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.IgnoreReturn Or BindingFlags.InvokeMethod, Nothing, New Object() {"Brad", "Smith"}, Nothing)

        ' BindingFlags.OptionalParamBinding
        Console.WriteLine()
        Console.WriteLine("Using OptionalParamBinding and invoking the PrintName method.")
        Console.WriteLine("-------------------------------------------------------------")
        methInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.OptionalParamBinding Or BindingFlags.InvokeMethod, Nothing, New Object() {"Brad", "Smith"}, Nothing)

        ' BindingFlags.ExactBinding
        Console.WriteLine()
        Console.WriteLine("Using ExactBinding and invoking the PrintName method.")
        Console.WriteLine("-----------------------------------------------------")
        methInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.ExactBinding Or BindingFlags.InvokeMethod, Nothing, New Object() {"Brad", "Smith"}, Nothing)

        ' BindingFlags.FlattenHierarchy
        Console.WriteLine()
        Console.WriteLine("Using FlattenHierarchy and invoking the PrintName method.")
        Console.WriteLine("---------------------------------------------------------")
        methInfo = obj.GetType().GetMethod("PrintName")
        methInfo.Invoke(obj, BindingFlags.FlattenHierarchy Or BindingFlags.InvokeMethod, Nothing, New Object() {"Brad", "Smith"}, Nothing)
    End Sub 'Go
End Class 'Invoke

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()
        Name = "initialName"
    End Sub 'New

    Private methodCalled As Integer = 0


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


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


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


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


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


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

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

    Public Sub PrintTime()
        Console.WriteLine(DateTime.Now)
    End Sub 'PrintTime
End Class 'TestClass2
using System;
using System.Reflection;
using System.IO;

namespace BindingFlagsSnippet
{
    class EntryPoint
    {
        static void Main(string[] args)
        {
            Invoke.Go();
        }
    }

    
    class Invoke
    {
        public static void Go()
        {
            // 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, 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 by reference.
            Console.WriteLine();
            Console.WriteLine("Invoking a method by reference.");
            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]);
            // The string is case-sensitive.
            Type type = Type.GetType("System.String");

            // Check to see if the value is valid. If the object is null, the type does not exist.
            if (type == null) 
            {
                Console.WriteLine("Please ensure that you specify only valid types in the type field.");
                Console.WriteLine("The type name is case-sensitive.");
                return;
            }
            // Declare and populate the arrays to hold the information.
            // You must declare either NonPublic or Public with Static or the search will not work.
            FieldInfo [] fi = type.GetFields (BindingFlags.Static |
                BindingFlags.NonPublic | BindingFlags.Public);  
            // BindingFlags.NonPublic 
            MethodInfo [] miNonPublic = type.GetMethods (BindingFlags.Static |
                BindingFlags.NonPublic);
            // BindingFlags.Public
            MethodInfo [] miPublic = type.GetMethods (BindingFlags.Static |
                BindingFlags.Public);

            // Iterate through all the nonpublic methods.
            foreach (MethodInfo method in miNonPublic) 
            {
                Console.WriteLine(method);
            }
            // Iterate through all the public methods.
            foreach (MethodInfo method in miPublic) 
            {
                Console.WriteLine(method);
            }
            // Iterate through all the fields.
            foreach (FieldInfo f in fi) 
            {
                Console.WriteLine(f);
            }

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

            // BindingFlags.CreateInstance
            // Calling and creating an instance method.
            Console.WriteLine();
            Console.WriteLine("Invoking and creating an instance method.");
            Console.WriteLine("-----------------------------------------");
            tc.GetType().InvokeMember ("AddUp", BindingFlags.Public | 
                BindingFlags.Instance | BindingFlags.CreateInstance, 
                null, tc, new object [] {});

            // BindingFlags.DeclaredOnly
            TestClass tc2 = new TestClass();
            Console.WriteLine();
            Console.WriteLine("DeclaredOnly members");
            Console.WriteLine("---------------------------------");
            System.Reflection.MemberInfo[] memInfo = 
                tc2.GetType().GetMembers(BindingFlags.DeclaredOnly);
            for(int i=0;i<memInfo.Length;i++) 
            {
                Console.WriteLine(memInfo[i].Name);
            }

            // BindingFlags.SuppressChangeType
            TestClass obj = new TestClass();
            Console.WriteLine();
            Console.WriteLine("Invoking static method - PrintName");
            Console.WriteLine("---------------------------------");
            System.Reflection.MethodInfo methInfo = 
                obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.SuppressChangeType | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"Brad","Smith"},null);

            // BindingFlags.IgnoreCase
            Console.WriteLine();
            Console.WriteLine("Using IgnoreCase and invoking the PrintName method.");
            Console.WriteLine("---------------------------------------------------");
            methInfo = obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.IgnoreCase | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"brad","smith"},null);

            // BindingFlags.IgnoreReturn
            Console.WriteLine();
            Console.WriteLine("Using IgnoreReturn and invoking the PrintName method.");
            Console.WriteLine("-----------------------------------------------------");
            methInfo = obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.IgnoreReturn | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"Brad","Smith"},null);

            // BindingFlags.OptionalParamBinding
            Console.WriteLine();
            Console.WriteLine("Using OptionalParamBinding and invoking the PrintName method.");
            Console.WriteLine("-------------------------------------------------------------");
            methInfo = obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.OptionalParamBinding | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"Brad","Smith"},null);

            // BindingFlags.ExactBinding
            Console.WriteLine();
            Console.WriteLine("Using ExactBinding and invoking the PrintName method.");
            Console.WriteLine("-----------------------------------------------------");
            methInfo = obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.ExactBinding | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"Brad","Smith"},null);
 
            // BindingFlags.FlattenHierarchy
            Console.WriteLine();
            Console.WriteLine("Using FlattenHierarchy and invoking the PrintName method.");
            Console.WriteLine("---------------------------------------------------------");
            methInfo = obj.GetType().GetMethod("PrintName");
            methInfo.Invoke(obj,BindingFlags.FlattenHierarchy | 
                BindingFlags.InvokeMethod, null,new object[] 
                {"Brad","Smith"},null);
        }
    }

    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 ()
        {
            Name = "initialName";
        }

        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);
        }
    }
}
using namespace System;
using namespace System::Collections;
using namespace System::Reflection;
using namespace System::IO;

//namespace BindingFlagsSnippet {
public ref class TestClass
{
public:
   String^ Name;

private:
   array<Object^>^values;

public:

   property Object^ Item [int]
   {
      Object^ get( int index )
      {
         return values[ index ];
      }

      void set( int index, Object^ value )
      {
         values[ index ] = value;
      }

   }

   property Object^ Value 
   {
      Object^ get()
      {
         return "the value";
      }

   }
   int methodCalled;
   TestClass()
   {
      Name = "initialName";
      array<Object^>^o = {(int^)0,1,2,3,4,5,6,7,8,9};
      values = o;
      methodCalled = 0;
   }

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

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

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

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

   void PrintTime()
   {
      Console::WriteLine( DateTime::Now );
   }

   void Swap( interior_ptr<int> a, interior_ptr<int> b )
   {
      int x =  *a;
       *a =  *b;
       *b = x;
   }

};


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

};

class Invoke
{
public:
   static void Go()
   {
      
      // BindingFlags::InvokeMethod
      // Call a static method.
      Type^ t = TestClass::typeid;
      Console::WriteLine();
      Console::WriteLine( "Invoking a static method." );
      Console::WriteLine( "-------------------------" );
      array<Object^>^obj1;
      t->InvokeMember( "SayHello", BindingFlags::InvokeMethod, nullptr, nullptr, obj1 );
      
      // BindingFlags::InvokeMethod
      // Call an instance method.
      TestClass^ c = gcnew TestClass;
      Console::WriteLine();
      Console::WriteLine( "Invoking an instance method." );
      Console::WriteLine( "----------------------------" );
      c->GetType()->InvokeMember( "AddUp", BindingFlags::InvokeMethod, nullptr, c, obj1 );
      c->GetType()->InvokeMember( "AddUp", BindingFlags::InvokeMethod, nullptr, c, obj1 );
      
      // BindingFlags::InvokeMethod
      // Call a method with parameters.
      array<Object^>^args = {100.09,184.45};
      Object^ result;
      Console::WriteLine();
      Console::WriteLine( "Invoking a method with parameters." );
      Console::WriteLine( "---------------------------------" );
      result = t->InvokeMember( "ComputeSum", BindingFlags::InvokeMethod, nullptr, nullptr, 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, nullptr, c, obj1 );
      Console::WriteLine( "Name == {0}", result );
      
      // Set a field.
      array<Object^>^obj2 = {"NewName"};
      t->InvokeMember( "Name", BindingFlags::SetField, nullptr, c, obj2 );
      result = t->InvokeMember( "Name", BindingFlags::GetField, nullptr, c, obj1 );
      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;
      array<Object^>^obj3 = {index};
      result = t->InvokeMember( "Item", BindingFlags::GetProperty, nullptr, c, obj3 );
      Console::WriteLine( "Item->Item[ {0}] == {1}", index, result );
      
      // BindingFlags::SetProperty
      // Set an indexed property value.
      index = 3;
      array<Object^>^obj4 = {index,"NewValue"};
      t->InvokeMember( "Item", BindingFlags::SetProperty, nullptr, c, obj4 );
      result = t->InvokeMember( "Item", BindingFlags::GetProperty, nullptr, c, obj3 );
      Console::WriteLine( "Item->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", static_cast<BindingFlags>(BindingFlags::GetField | BindingFlags::GetProperty), nullptr, c, obj1 );
      Console::WriteLine( "Name == {0}", result );
      
      // BindingFlags::GetProperty
      result = t->InvokeMember( "Value", static_cast<BindingFlags>(BindingFlags::GetField | BindingFlags::GetProperty), nullptr, c, obj1 );
      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.
      array<Object^>^argValues = {"Mouse","Micky"};
      array<String^>^argNames = {"lastName","firstName"};
      t->InvokeMember( "PrintName", BindingFlags::InvokeMethod, nullptr, nullptr, argValues, nullptr, nullptr, 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 = TestClass2::typeid;
      t3->InvokeMember( "", static_cast<BindingFlags>(BindingFlags::InvokeMethod | BindingFlags::Default), nullptr, gcnew TestClass2, obj1 );
      
      // BindingFlags::Static, NonPublic, and Public
      // Invoking a member by reference.
      Console::WriteLine();
      Console::WriteLine( "Invoking a method by reference." );
      Console::WriteLine( "-------------------------------" );
      MethodInfo^ m = t->GetMethod( "Swap" );
      args = gcnew array<Object^>(2);
      args[ 0 ] = 1;
      args[ 1 ] = 2;
      m->Invoke( gcnew TestClass, args );
      Console::WriteLine( "{0}, {1}", args[ 0 ], args[ 1 ] );
      
      // The String* is case-sensitive.
      Type^ type = Type::GetType( "System.String" );
      
      // Check to see if the value is valid. If the Object* is 0, the type does not exist.
      if ( type == nullptr )
      {
         Console::WriteLine( "Please ensure that you specify only valid types in the type field." );
         Console::WriteLine( "The type name is case-sensitive." );
         return;
      }

      
      // Declare and populate the arrays to hold the information.
      // You must declare either NonPublic or Public with Static or the search will not work.
      array<FieldInfo^>^fi = type->GetFields( static_cast<BindingFlags>(BindingFlags::Static | BindingFlags::NonPublic | BindingFlags::Public) );
      
      // BindingFlags::NonPublic 
      array<MethodInfo^>^miNonPublic = type->GetMethods( static_cast<BindingFlags>(BindingFlags::Static | BindingFlags::NonPublic) );
      
      // BindingFlags::Public
      array<MethodInfo^>^miPublic = type->GetMethods( static_cast<BindingFlags>(BindingFlags::Static | BindingFlags::Public) );
      
      // Iterate through all the nonpublic methods.
      IEnumerator^ myEnum1 = miNonPublic->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         MethodInfo^ method = safe_cast<MethodInfo^>(myEnum1->Current);
         Console::WriteLine( method );
      }

      IEnumerator^ myEnum2 = miPublic->GetEnumerator();
      while ( myEnum2->MoveNext() )
      {
         MethodInfo^ method = safe_cast<MethodInfo^>(myEnum2->Current);
         Console::WriteLine( method );
      }

      IEnumerator^ myEnum3 = fi->GetEnumerator();
      while ( myEnum3->MoveNext() )
      {
         FieldInfo^ f = safe_cast<FieldInfo^>(myEnum3->Current);
         Console::WriteLine( f );
      }

      
      // BindingFlags::Instance
      // Call an instance method.
      TestClass^ tc = gcnew TestClass;
      Console::WriteLine();
      Console::WriteLine( "Invoking an Instance method." );
      Console::WriteLine( "----------------------------" );
      tc->GetType()->InvokeMember( "AddUp", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance | BindingFlags::CreateInstance), nullptr, tc, obj1 );
      
      // BindingFlags::CreateInstance
      // Calling and creating an instance method.
      Console::WriteLine();
      Console::WriteLine( "Invoking and creating an instance method." );
      Console::WriteLine( "-----------------------------------------" );
      tc->GetType()->InvokeMember( "AddUp", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance | BindingFlags::CreateInstance), nullptr, tc, obj1 );
      
      // BindingFlags::DeclaredOnly
      TestClass^ tc2 = gcnew TestClass;
      Console::WriteLine();
      Console::WriteLine( "DeclaredOnly members" );
      Console::WriteLine( "---------------------------------" );
      array<System::Reflection::MemberInfo^>^memInfo = tc2->GetType()->GetMembers( BindingFlags::DeclaredOnly );
      for ( int i = 0; i < memInfo->Length; i++ )
      {
         Console::WriteLine( memInfo[ i ]->Name );

      }
      
      // BindingFlags::SuppressChangeType
      TestClass^ obj = gcnew TestClass;
      Console::WriteLine();
      Console::WriteLine( "Invoking static method - PrintName" );
      Console::WriteLine( "---------------------------------" );
      System::Reflection::MethodInfo^ methInfo = obj->GetType()->GetMethod( "PrintName" );
      array<Object^>^args1 = {"Brad","Smith"};
      methInfo->Invoke( obj, static_cast<BindingFlags>(BindingFlags::SuppressChangeType | BindingFlags::InvokeMethod), nullptr, args1, nullptr );
      
      // BindingFlags::IgnoreCase
      Console::WriteLine();
      Console::WriteLine( "Using IgnoreCase and invoking the PrintName method." );
      Console::WriteLine( "---------------------------------------------------" );
      methInfo = obj->GetType()->GetMethod( "PrintName" );
      array<Object^>^args2 = {"brad","smith"};
      methInfo->Invoke( obj, static_cast<BindingFlags>(BindingFlags::IgnoreCase | BindingFlags::InvokeMethod), nullptr, args2, nullptr );
      
      // BindingFlags::IgnoreReturn
      Console::WriteLine();
      Console::WriteLine( "Using IgnoreReturn and invoking the PrintName method." );
      Console::WriteLine( "-----------------------------------------------------" );
      methInfo = obj->GetType()->GetMethod( "PrintName" );
      array<Object^>^args3 = {"Brad","Smith"};
      methInfo->Invoke( obj, static_cast<BindingFlags>(BindingFlags::IgnoreReturn | BindingFlags::InvokeMethod), nullptr, args3, nullptr );
      
      // BindingFlags::OptionalParamBinding
      Console::WriteLine();
      Console::WriteLine( "Using OptionalParamBinding and invoking the PrintName method." );
      Console::WriteLine( "-------------------------------------------------------------" );
      methInfo = obj->GetType()->GetMethod( "PrintName" );
      array<Object^>^args4 = {"Brad","Smith"};
      methInfo->Invoke( obj, static_cast<BindingFlags>(BindingFlags::OptionalParamBinding | BindingFlags::InvokeMethod), nullptr, args4, nullptr );
      
      // BindingFlags::ExactBinding
      Console::WriteLine();
      Console::WriteLine( "Using ExactBinding and invoking the PrintName method." );
      Console::WriteLine( "-----------------------------------------------------" );
      methInfo = obj->GetType()->GetMethod( "PrintName" );
      array<Object^>^args5 = {"Brad","Smith"};
      methInfo->Invoke( obj, static_cast<BindingFlags>(BindingFlags::ExactBinding | BindingFlags::InvokeMethod), nullptr, args5, nullptr );
      
      // BindingFlags::FlattenHierarchy
      Console::WriteLine();
      Console::WriteLine( "Using FlattenHierarchy and invoking the PrintName method." );
      Console::WriteLine( "---------------------------------------------------------" );
      methInfo = obj->GetType()->GetMethod( "PrintName" );
      array<Object^>^args6 = {"Brad","Smith"};
      methInfo->Invoke( obj, static_cast<BindingFlags>(BindingFlags::FlattenHierarchy | BindingFlags::InvokeMethod), nullptr, args6, nullptr );
   }

};

int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   Invoke::Go();
}

//}
package BindingFlagsSnippet; 

import System.*;
import System.Reflection.*;
import System.IO.*;
   
class EntryPoint
{
    public static void main(String[] args)
    {
        Invoke.Go();
    } //main
} //EntryPoint
   
class Invoke
{
    public static void Go()
    {
        // BindingFlags.InvokeMethod
        // Call a static method.
        Type t = TestClass.class.ToType();

        Console.WriteLine();
        Console.WriteLine("Invoking a static method.");
        Console.WriteLine("-------------------------");
        t.InvokeMember("SayHello", BindingFlags.InvokeMethod, 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[] { (System.Double)100.09, 
            (System.Double)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[] { (Int32)index });
        Console.WriteLine("Item[{0}] == {1}", (Int32)index, result);

        // BindingFlags.SetProperty
        // Set an indexed property value.
        index = 3;
        t.InvokeMember("Item", BindingFlags.SetProperty, null, c, 
            new Object[] { (Int32)index, "NewValue" });
        result = t.InvokeMember("Item", BindingFlags.GetProperty, null, c, 
            new Object[] { (Int32)index });
        Console.WriteLine("Item[{0}] == {1}", (Int32)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 = TestClass2.class.ToType();
        t3.InvokeMember("", BindingFlags.InvokeMethod | BindingFlags.Default, 
            null, new TestClass2(), new Object[]{});

        // BindingFlags.Static, NonPublic, and Public
        // Invoking a member by reference.
        Console.WriteLine();
        Console.WriteLine("Invoking a method by reference.");
        Console.WriteLine("-------------------------------");

        MethodInfo m = t.GetMethod("Swap");

        args = new Object[2];
        args[0] = (Int32)1;
        args[1] = (Int32)2;
        m.Invoke(new TestClass(), args);
        Console.WriteLine("{0}, {1}", args[0], args[1]);

        // The string is case-sensitive.
        Type type = Type.GetType("System.String");

        // Check to see if the value is valid. If the object is null, 
        // the type does not exist.
        if (type == null) {
            Console.WriteLine("Please ensure that you specify only valid types "
                + "in the type field.");
            Console.WriteLine("The type name is case-sensitive.");
            return;
        }

        // Declare and populate the arrays to hold the information.
        // You must declare either NonPublic or Public with Static or the 
        // search will not work.
        FieldInfo fi[] = type.GetFields(
            BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        // BindingFlags.NonPublic 
        MethodInfo miNonPublic[] = type.GetMethods(
            BindingFlags.Static | BindingFlags.NonPublic);

        // BindingFlags.Public
        MethodInfo miPublic[] = type.GetMethods(
            BindingFlags.Static | BindingFlags.Public);

        // Iterate through all the nonpublic methods.
        for (int iCtr = 0; iCtr < miNonPublic.length; iCtr++) {
            MethodInfo method = (MethodInfo)miNonPublic.get_Item(iCtr);
            Console.WriteLine(method);
        }

        // Iterate through all the public methods.
        for (int iCtr = 0; iCtr < miPublic.length; iCtr++) {
            MethodInfo method = (MethodInfo)miPublic.get_Item(iCtr);
            Console.WriteLine(method);
        }

        // Iterate through all the fields.
        for (int iCtr = 0; iCtr < fi.length; iCtr++) {
            FieldInfo f = (FieldInfo)fi.get_Item(iCtr);
            Console.WriteLine(f);
        }

        // BindingFlags.Instance
        // Call an instance method.
        TestClass tc = new TestClass();

        Console.WriteLine();
        Console.WriteLine("Invoking an Instance method.");
        Console.WriteLine("----------------------------");
        tc.GetType().InvokeMember("AddUp", BindingFlags.Public 
            | BindingFlags.Instance | BindingFlags.CreateInstance, null, tc, 
            new Object[]{});

        // BindingFlags.CreateInstance
        // Calling and creating an instance method.
        Console.WriteLine();
        Console.WriteLine("Invoking and creating an instance method.");
        Console.WriteLine("-----------------------------------------");
        tc.GetType().InvokeMember("AddUp", BindingFlags.Public 
            | BindingFlags.Instance | BindingFlags.CreateInstance, null, tc, 
            new Object[]{});

        // BindingFlags.DeclaredOnly
        TestClass tc2 = new TestClass();

        Console.WriteLine();
        Console.WriteLine("DeclaredOnly members");
        Console.WriteLine("---------------------------------");

        System.Reflection.MemberInfo memInfo[] = tc2.GetType().
            GetMembers(BindingFlags.DeclaredOnly);
        for (int i = 0; i < memInfo.length; i++) {
            Console.WriteLine(((System.Reflection.MemberInfo)memInfo.
                get_Item(i)).get_Name());
        }

        // BindingFlags.SuppressChangeType
        TestClass obj = new TestClass();

        Console.WriteLine();
        Console.WriteLine("Invoking static method - PrintName");
        Console.WriteLine("---------------------------------");
        System.Reflection.MethodInfo methInfo = obj.GetType().
            GetMethod("PrintName");
        methInfo.Invoke(obj, 
            BindingFlags.SuppressChangeType | BindingFlags.InvokeMethod, null, 
            new Object[] { "Brad", "Smith" }, null);

        // BindingFlags.IgnoreCase
        Console.WriteLine();
        Console.WriteLine("Using IgnoreCase and invoking the PrintName method.");
        Console.WriteLine("---------------------------------------------------");
        methInfo = obj.GetType().GetMethod("PrintName");
        methInfo.Invoke(obj, 
            BindingFlags.IgnoreCase | BindingFlags.InvokeMethod, null, 
            new Object[] { "brad", "smith" }, null);

        // BindingFlags.IgnoreReturn
        Console.WriteLine();
        Console.WriteLine("Using IgnoreReturn and invoking the PrintName "
            + "method.");
        Console.WriteLine("----------------------------------------------"
            + "-------");
        methInfo = obj.GetType().GetMethod("PrintName");
        methInfo.Invoke(obj, 
            BindingFlags.IgnoreReturn | BindingFlags.InvokeMethod, null, 
            new Object[] { "Brad", "Smith" }, null);

        // BindingFlags.OptionalParamBinding
        Console.WriteLine();
        Console.WriteLine("Using OptionalParamBinding and invoking the "
            + "PrintName method.");
        Console.WriteLine("-------------------------------------------------"
            + "------------");
        methInfo = obj.GetType().GetMethod("PrintName");
        methInfo.Invoke(obj, 
            BindingFlags.OptionalParamBinding | BindingFlags.InvokeMethod, 
            null, new Object[] { "Brad", "Smith" }, null);

        // BindingFlags.ExactBinding
        Console.WriteLine();
        Console.WriteLine("Using ExactBinding and invoking the PrintName "
            + "method.");
        Console.WriteLine("-------------------------------------------------"
            + "----");
        methInfo = obj.GetType().GetMethod("PrintName");
        methInfo.Invoke(obj, 
            BindingFlags.ExactBinding | BindingFlags.InvokeMethod, null, 
            new Object[] { "Brad", "Smith" }, null);

        // BindingFlags.FlattenHierarchy
        Console.WriteLine();
        Console.WriteLine("Using FlattenHierarchy and invoking the PrintName "
            + "method.");
        Console.WriteLine("---------------------------------------------------"
            + "------");
        methInfo = obj.GetType().GetMethod("PrintName");
        methInfo.Invoke(obj, 
            BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod, null, 
            new Object[] { "Brad", "Smith" }, null);
    } //Go
} //Invoke
      
public class TestClass
{
    public String name;
    private Object values[] = new Object[] { (Int32)0, (Int32)1, (Int32)2, 
        (Int32)3, (Int32)4, (Int32)5, (Int32)6, (Int32)7, (Int32)8, (Int32)9 };

    /** @property 
     */
    public Object get_Item(int index)
    {
        return values.get_Item(index);
    } //get_Item

    /** @property 
     */
    public void set_Item(int index, Object value)
    {
        values.set_Item(index, value);
    } //set_Item

    /** @property 
     */
    public Object get_Value()
    {
        return "the value";
    } //get_Value

    public TestClass()
    {
        name = "initialName";
    } //TestClass

    private int methodCalled = 0;

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

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

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

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

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

    public void Swap(int a, int b)
    {
        int x = a;
        a = b;
        b = x;
    } //Swap
} //TestClass 
   
/** @attribute DefaultMemberAttribute("PrintTime")
 */
 public class TestClass2
 {
     public void PrintTime()
     {
         Console.WriteLine(DateTime.get_Now());
     } //PrintTime
 } //TestClass2

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

System.Reflection 네임스페이스