小编Meh*_*fuz的帖子

有没有办法通过反思知道一个方法是来自调用者的汇编?

我们考虑以下代码:

internal class FooInternal
{
    internal static void DoIt()
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个库,里面反映了FooInternal类型,对于一个反映的methodInfo(在这种情况下是DoIt)我有这个:

if ((methodInfo.Attributes & MethodAttributes.FamANDAssem) == MethodAttributes.FamANDAssem)
{
     // hits here.
}
Run Code Online (Sandbox Code Playgroud)

我们可以看到我正在使用标记为FarmAndAssem的内部方法.现在,我还需要确保该方法在调用它的同一个程序集中被延迟,这样我的libary就不会在其他程序集中定义的类型中标记为internal的成员行.

我不能在反映方法的库中使用Assembly.GetExecutingAssembly,因为它将返回库所在的程序集,而不是使用库声明/调用类型的程序集.

因此,代码应确保以下工作流程:

 Given: FooInternal is declared in the same asssembly as the caller's assembly. 
 When: Called with MyLib.Fake(typeof(FooInternal)); 
 Then: It will hit the expected line.
 Given: A third-party type. 
 When: Called with MyLib.Fake(typeof(FileInfo)); 
 Then: It will not hit  the expected line even though *FileInfo* 
 has internal methods and as such …

.net c# reflection

0
推荐指数
1
解决办法
173
查看次数

标签 统计

.net ×1

c# ×1

reflection ×1