T_Cyjb_Reflection_PowerBinder - CYJB/Cyjb GitHub Wiki

PowerBinder 类

从候选者列表中选择一个成员,并执行实参类型到形参类型的类型转换。 在选择时,支持对泛型方法进行选择,并允许进行强制类型转换。

继承层次

System.Object
  System.Reflection.Binder
    Cyjb.Reflection.PowerBinder
Namespace: Cyjb.Reflection
Assembly: Cyjb (in Cyjb.dll) Version: 1.0.23+7750dd8e971297c5fa962a3bee37fb78f72793f6

语法

C#

[SerializableAttribute]
public sealed class PowerBinder : Binder

The PowerBinder type exposes the following members.

属性

 

名称 说明
公共属性静态成员 Default 获取默认的 PowerBinder 实例。
公共属性静态成员 Explicit 获取可以进行显式类型转换的 PowerBinder 实例。
  Back to Top

方法

 

名称 说明
公共方法 BindToField 基于指定的判据,从给定的字段集中选择一个字段。 (重写 Binder.BindToField(BindingFlags, FieldInfo[], Object, CultureInfo).)
公共方法 BindToMethod 基于提供的参数,从给定的方法集中选择要调用的方法。 (重写 Binder.BindToMethod(BindingFlags, MethodBase[], Object[], ParameterModifier[], CultureInfo, String[], Object).)
公共方法 ChangeType 将给定 Object 的类型更改为给定 Type。 (重写 Binder.ChangeType(Object, Type, CultureInfo).)
公共方法 Equals Determines whether the specified object is equal to the current object. (继承自 Object。)
公共方法 GetHashCode Serves as the default hash function. (继承自 Object。)
公共方法 GetType Gets the Type of the current instance. (继承自 Object。)
公共方法 ReorderArgumentArray BindToMethod(BindingFlags, MethodBase[], Object[], ParameterModifier[], CultureInfo, String[], Object) 返回后,将 args 参数还原为从 BindToMethod(BindingFlags, MethodBase[], Object[], ParameterModifier[], CultureInfo, String[], Object) 传入时的状态。 (重写 Binder.ReorderArgumentArray(Object[], Object).)
公共方法 SelectMethod 基于参数类型,从给定的方法集中选择一个方法。 允许通过指定 OptionalParamBinding 来匹配可选参数。 (重写 Binder.SelectMethod(BindingFlags, MethodBase[], Type[], ParameterModifier[]).)
公共方法 SelectProperty 基于参数类型,从给定的属性集中选择一个属性。 (重写 Binder.SelectProperty(BindingFlags, PropertyInfo[], Type, Type[], ParameterModifier[]).)
公共方法 ToString Returns a string that represents the current object. (继承自 Object。)
  Back to Top

Remarks

PowerBinder 类是对 Binder 类的扩展, 支持泛型方法和强制类型转换,可以有效的扩展反射得到类型成员的过程。

关于 Binder 类的原理,以及 PowerBinder 类的实现,可以参见我的博文 《C# 使用 Binder 类自定义反射》

关于进行泛型类型推断的原理,可以参考我的博文 《C# 泛型方法的类型推断》

示例

下面的例子演示了 PowerBinder 对泛型方法和强制类型转换的支持。

class TestClass {
    public static void TestMethod(int value) { }
    public static void TestMethod2<T>(T value) { }
}
Type outputType = typeof(TestClass);
Console.WriteLine(outputType.GetMethod("TestMethod", new Type[] { typeof(long) }));
Console.WriteLine(outputType.GetMethod("TestMethod", BindingFlags.Static | BindingFlags.Public, 
    PowerBinder.CastBinder, new Type[] { typeof(long) }, null));
Console.WriteLine(outputType.GetMethod("TestMethod2", new Type[] { typeof(string) }));
Console.WriteLine(outputType.GetMethod("TestMethod2", BindingFlags.Static | BindingFlags.Public, 
    PowerBinder.DefaultBinder, new Type[] { typeof(string) }, null));

参见

Reference

Cyjb.Reflection 命名空间

Other Resources

《C# 使用 Binder 类自定义反射》
《C# 泛型方法的类型推断》
⚠️ **GitHub.com Fallback** ⚠️