BindingFlags 枚举

定义

指定控制绑定以及通过反射执行成员和类型搜索的方式的标记。

此枚举支持其成员值的按位组合。

C#
[System.Flags]
public enum BindingFlags
C#
[System.Flags]
[System.Serializable]
public enum BindingFlags
C#
[System.Flags]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum BindingFlags
继承
BindingFlags
属性

字段

名称 说明
CreateInstance 512

指定反射应创建指定类型的实例。 调用与给定参数匹配的构造函数。 忽略提供的成员名称。 如果未指定查找的类型,则应用“(实例 | 公共)”。 不能调用类型初始值设定项。

此标志会传递给 InvokeMember 方法以调用构造函数。

DeclaredOnly 2

指定只应考虑在所提供类型的层次结构级别上声明的成员。 不考虑继承的成员。

Default 0

指定未定义任何绑定标志。

DoNotWrapExceptions 33554432
ExactBinding 65536

指定提供的参数的类型必须与对应形参的类型完全匹配。 如果调用方提供非 null Binder 对象,则反射会引发异常,因为这意味着调用方在提供将选取适当方法的 BindToXXX 实现。 当自定义绑定器可实现此标志的语义时,默认绑定器会忽略此标志。

FlattenHierarchy 64

指定应返回层次结构往上的公共成员和受保护静态成员。 不返回继承类中的私有静态成员。 静态成员包括字段、方法、事件和属性。 不支持嵌套类型。

GetField 1024

指定应返回指定字段的值。

此标志会传递给 InvokeMember 方法以获取字段值。

GetProperty 4096

指定应返回指定属性的值。

此标志会传递给 InvokeMember 方法以调用属性 getter。

IgnoreCase 1

指定在绑定时不应考虑成员名称的大小写。

IgnoreReturn 16777216

在 COM 互操作中用于指定可以忽略成员的返回值。

Instance 4

指定实例成员要包括在搜索中。

InvokeMethod 256

指定要调用的方法。 这不必是构造函数或类型初始值设定项。

此标志会传递给 InvokeMember 方法以调用方法。

NonPublic 32

指定非公共成员要包括在搜索中。

OptionalParamBinding 262144

返回其参数计数与提供的参数数量匹配的成员集。 此绑定标志用于参数具有默认值的方法和使用变量参数 (varargs) 的方法。 此标志只应与 InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) 结合使用。

使用默认值的参数仅在省略了尾随参数的调用中使用。 它们必须是位于最后面的参数。

Public 16

指定公共成员要包括在搜索中。

PutDispProperty 16384

指定应调用 COM 对象上的 PROPPUT 成员。 PROPPUT 指定使用值的属性设置函数。 如果属性同时具有 PROPPUTPROPPUTREF 并且你需要区分调用哪一个,请使用 PutDispProperty

PutRefDispProperty 32768

指定应调用 COM 对象上的 PROPPUTREF 成员。 PROPPUTREF 指定使用引用而不是值的属性设置函数。 如果属性同时具有 PROPPUTPROPPUTREF 并且你需要区分调用哪一个,请使用 PutRefDispProperty

SetField 2048

指定应设置指定字段的值。

此标志会传递给 InvokeMember 方法以设置字段值。

SetProperty 8192

指定应设置指定属性的值。 对于 COM 属性,指定此绑定标志等效于指定 PutDispPropertyPutRefDispProperty

此标志会传递给 InvokeMember 方法以调用属性 setter。

Static 8

指定静态成员要包括在搜索中。

SuppressChangeType 131072

未实现。

示例

以下示例演示了许多绑定标志。

C#
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.
-------------------------

 */

注解

这些BindingFlags控件绑定适用于 、 System.ReflectionSystem.Runtime 命名空间中的System许多类,这些类调用、创建、获取、设置和查找成员和类型。

BindingFlags 用于以下 Type 方法和其他位置,例如 MethodBase.Invoke

InvokeMemberGetMethod 尤其重要。

绑定标志可以按标识类型成员的方式进行分类,如下表所示。

由辅助功能标识 由绑定参数标识 由操作标识
DeclaredOnly

FlattenHierarchy

IgnoreCase

IgnoreReturn

实例

NonPublic

公用

静态
ExactBinding

OptionalParamBinding
CreateInstance

GetField

SetField

GetProperty

SetProperty

InvokeMethod

PutDispProperty

PutRefDispProperty

备注

必须同时指定 InstanceStaticPublicNonPublic ,否则将不返回任何成员。

下表列出了默认 Binder.ChangeType执行的强制操作。 此表尤其适用于 BindingFlags.ExactBinding 绑定标志。 一般原则是, ChangeType 应仅执行扩大强制,这永远不会丢失数据。 扩大强制转换的一个示例是将 32 位有符号整数的值强制转换为 64 位带符号整数的值。 这与收缩强制(可能会丢失数据)区别开来。 收缩强制的一个示例是将 64 位有符号整数强制转换为 32 位有符号整数。

源类型 目标类型
任何类型 其基类型。
任何类型 它实现的接口。
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
非引用 按引用。

BindingFlags.ExactBinding使用绑定标志时,反射对通用类型系统的可访问性规则进行建模。 例如,如果调用方位于同一程序集中,则调用方不需要内部成员的特殊权限。 否则,调用方需要 ReflectionPermission。 这与查找受保护成员、私有成员等保持一致。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.5, 1.6, 2.0, 2.1
UWP 10.0