如何利用反射调用显式实现的静态抽象接口方法?
问题:反射调用显式实现的泛型接口静态方法
泛型接口定义
public interface IMyInterface<T> { static abstract int GetNumber(); }
实现接口的类
public class MyClass1 : IMyInterface<Company>, IMyInterface<Person> { static int IMyInterface<Company>.GetNumber() => 1; static int IMyInterface<Person>.GetNumber() => 2; } public class MyClass2 : IMyInterface<Company>, IMyInterface<Person> { static int IMyInterface<Company>.GetNumber() => 3; static int IMyInterface<Person>.GetNumber() => 4; }
需要实现的消费方法
现有如下方法框架,需补全实现,使其能根据传入的类类型和泛型参数类型,调用对应显式实现的GetNumber静态方法并返回结果:
public int GetNumbers(Type classType, Type genericType) { Type interfaceType = typeof(IMyInterface<>).MakeGenericType(genericType); return ?????? }
预期调用结果:
GetNumbers(typeof(MyClass1), typeof(Company)); // 返回1 GetNumbers(typeof(MyClass1), typeof(Person)); // 返回2 GetNumbers(typeof(MyClass2), typeof(Company)); // 返回3 GetNumbers(typeof(MyClass2), typeof(Person)); // 返回4
(注:原提问中最后一行标注返回3应为笔误,实际对应实现返回4)
实现方案
由于是显式实现的接口静态方法,无法直接通过类类型获取该方法,必须通过对应的泛型接口类型查找方法后反射调用:
public int GetNumbers(Type classType, Type genericType) { Type interfaceType = typeof(IMyInterface<>).MakeGenericType(genericType); // 获取接口中定义的静态GetNumber方法 MethodInfo method = interfaceType.GetMethod(nameof(IMyInterface<object>.GetNumber), BindingFlags.Public | BindingFlags.Static); // 静态方法调用时无需实例,第一个参数传null return (int)method.Invoke(null, null); }
关键说明
- 显式实现的接口静态方法属于泛型接口实例类型,而非实现类的类型,因此必须通过
interfaceType定位方法 - 指定
BindingFlags.Public | BindingFlags.Static确保精准匹配目标静态方法 - 静态方法调用时,
Invoke的第一个参数传入null即可,无需提供类实例
内容的提问来源于stack exchange,提问作者Peter Morris
相关产品推荐
相关产品推荐

