简体   繁体   中英

Is there way to know through reflection that a method is from caller's assembly?

Let's consider the following code :

internal class FooInternal
{
    internal static void DoIt()
    {
        throw new NotImplementedException();
    }
}

Now i have a library inside which it is reflecting the FooInternal type and for a reflected methodInfo (in this case DoIt) i have this :

if ((methodInfo.Attributes & MethodAttributes.FamANDAssem) == MethodAttributes.FamANDAssem)
{
     // hits here.
}

We can see that i am hitting the line for an internal method that is marked as FarmAndAssem. Now, I also need to ensure that the method is delared in the same assembly from where it is invoked so that my libary does not end up hitting the line for members from type defined in other assembly and marked as internal.

I can't use Assembly.GetExecutingAssembly from within the library that reflects the method as it will return the assembly where the library resides not the assembly where type the is declared / invoked using the library.

Therefore, the code should ensure the following workflow:

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 the first condition passes, because 
 FileInfo belongs to a different assembly from caller's.

您可以从代码所在的类型中获取程序集: this.GetType().Assembly并将其与methodInfo.Module.Assembly进行比较。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM