我的问题是:如果我有 MethodInfo 对象,用于从接口类型获取的方法,并且我还有实现此接口的类的 Type 对象,但它通过显式实现来实现所述方法,如何正确获取该类中实现方法对应的MethodInfo对象?
我需要这样做的原因是实现方法可以应用一些属性,并且我需要通过反射找到这些属性,但是需要查找这些属性的类只有实现类的对象引用,并且类型接口的对象(+相应的 MethodInfo 对象)。
所以,假设我有以下程序:
using System;
using System.Reflection;
namespace ConsoleApplication8
{
public interface ITest
{
void Test();
}
public class Test : ITest
{
void ITest.Test()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
Type interfaceType = typeof(ITest);
Type classType = typeof(Test);
MethodInfo testMethodViaInterface =
interfaceType.GetMethods()[0];
MethodInfo implementingMethod =
classType.GetMethod(/* ??? */"Test");
Console.Out.WriteLine("interface: " +
testMethodViaInterface.Name);
if (implementingMethod != null)
Console.Out.WriteLine("class: " +
implementingMethod.Name);
else
Console.Out.WriteLine("class: unable to locate");
Console.Out.Write("Press enter to exit...");
Console.In.ReadLine();
}
}
}
运行这个给我:
interface: Test
class: unable to locate
Press enter to exit...
在代码中,有一个带有 ??? 的 .GetMethod 调用。评论。这部分是我需要帮助的。要么我需要在这里指定(并且我已经测试了很多,这使我采用了另一种方式),要么我需要用什么来替换此代码。
由于我使用了接口中方法的显式实现,因此该方法的实际名称不仅仅是“Test”。如果我使用以下代码转储类类型的 GetMethods() 数组的全部内容:
foreach (var mi in classType.GetMethods(
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
Console.Out.WriteLine(mi.Name);
}
然后我得到这个:
ConsoleApplication8.ITest.Test <-- this is the one I want
ToString
Equals
GetHashCode
GetType
Finalize
MemberwiseClone
显然,该名称前面有接口的全名及其命名空间。但是,由于重载,看起来我必须做的是在类中找到所有此类实现方法(即假设有多个随参数变化的 Test 方法),然后比较参数。
有更容易的方法吗?基本上,一旦我从接口中获得了某个方法的 MethodInfo 对象,我就想通过获取其 MethodInfo 对象来找到实现该方法的类的确切方法。
请注意,我在这里处于一个循环的情况,所以如果我必须循环遍历类中的方法以从接口中找到确切的方法,那没关系,只要我有一个好的方法来识别何时找到了正确对象,真爱。
我尝试像这样更改上面的循环:
foreach (var mi in classType.GetMethods(
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
if (mi.GetBaseDefinition() == testMethodViaInterface)
Console.Out.WriteLine(mi.Name);
}
这没有打印出任何东西,所以很清楚GetBaseDefinition
这种方法上的 不指向接口中的 MethodInfo 对象。
有什么指点吗?