【发布时间】:2012-08-14 09:41:13
【问题描述】:
让我们考虑以下代码:
internal class FooInternal
{
internal static void DoIt()
{
throw new NotImplementedException();
}
}
现在我有一个库,它在其中反映 FooInternal 类型,对于反射的 methodInfo(在本例中为 DoIt)我有这个:
if ((methodInfo.Attributes & MethodAttributes.FamANDAssem) == MethodAttributes.FamANDAssem)
{
// hits here.
}
我们可以看到我正在为标记为 FarmAndAssem 的内部方法打线。现在,我还需要确保该方法是在调用它的同一程序集中声明的,这样我的库就不会在其他程序集中定义并标记为内部的类型的成员出现在行中。
我不能在反映该方法的库中使用 Assembly.GetExecutingAssembly,因为它将返回库所在的程序集,而不是使用该库声明/调用类型的程序集。
因此,代码应确保以下工作流程:
给定: FooInternal 在与调用者程序集相同的程序集中声明。 何时:使用 MyLib.Fake(typeof(FooInternal)); 调用 然后:它将达到预期的线。 给定:第三方类型。 何时:使用 MyLib.Fake(typeof(FileInfo)); 调用 然后:即使 *FileInfo* 也不会达到预期的行 具有内部方法,因此第一个条件通过,因为 FileInfo 属于与调用者不同的程序集。【问题讨论】:
标签: c# .net reflection