【发布时间】:2015-08-02 00:09:38
【问题描述】:
我在我的一个 C# 项目中使用反射:它是面向 Windows 8.1 和 Windows Phone 8.1 的可移植类库。
在那个项目中,我有一个名为 IMyInterface 的接口,它有一个带有通用参数 TGenericObject 的方法 DoSomething。我还有一个名为 MyClass 的类。在某一时刻,我需要通过反射查找指定接口中的方法 DoSomething。因此,我将 Type 类中的 GetRuntimeMethod 方法与实际参数的类型一起使用,在我的示例中为 MyClass。
请记住,我在这里提供的示例只是为了突出我面临的问题。实际情况是,接口 IMyInterface 和类 MyClass 在另一个项目中。
这里是交易:我期待 GetRuntimeMethod 返回 DoSomething 方法的 MethodInfo,但它没有:返回 null。
我是否缺少从 IMyInterface 中找到 DoSomething 方法的简单方法,或者我必须更脏?
public interface IMyInterface
{
void DoSomething<TGenericObject>(TGenericObject myGenericObject);
}
public class MyClass
{ }
class Program
{
static void Main(string[] args)
{
MyClass myClassInst = new MyClass();
MethodInfo methodInfo = typeof (IMyInterface).GetRuntimeMethod("DoSomething", new [] { myClassInst.GetType() });
}
}
【问题讨论】:
-
MyClass没有实现IMyInterface。这可能是问题吗:) -
不幸的是,没有:( MyClass 并不意味着从 IMyInterface 派生。MyClass 实例是调用通用 DoSomething 方法所需的参数。
-
我在您的示例中没有看到任何实现
IMyInterface的内容。您希望如何找到“具体”的运行时方法? -
我认为此时不需要 IMyInterface 的实现,因为我试图通过反射找到的是接口中声明的 DoSomething 方法的 MethodInfo :S 但是,假设你添加一个名为 MyInterfaceImpl 的 IMyInterface 实现,并在 Main 方法中将 typeof(IMyInterface) 替换为 typeof(MyInterfaceImpl)。不幸的是,您得到的仍然是相同的结果:methodInfo 为空。 (顺便说一句,我提供的示例编译:))
-
@Kzrystof GetRuntimeMethod 不应该解决重载问题,因为您没有声明这样的方法,所以找不到它。
标签: c# generics reflection windows-runtime