Assembly.GetCallingAssembly 方法

定义

返回 Assembly 调用当前正在执行的方法的方法。

public:
 static System::Reflection::Assembly ^ GetCallingAssembly();
public static System.Reflection.Assembly GetCallingAssembly();
static member GetCallingAssembly : unit -> System.Reflection.Assembly
Public Shared Function GetCallingAssembly () As Assembly

返回

Assembly调用当前正在执行的方法的对象。

示例

以下示例获取当前方法的调用程序集。

// Assembly FirstAssembly
using System;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace FirstAssembly
{
    public class InFirstAssembly
    {
        public static void Main()
        {
            FirstMethod();
            SecondAssembly.InSecondAssembly.OtherMethod();
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void FirstMethod()
        {
            Console.WriteLine("FirstMethod called from: " + Assembly.GetCallingAssembly().FullName);
        }
    }
}

// Assembly SecondAssembly
namespace SecondAssembly
{
    class InSecondAssembly
    {
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void OtherMethod()
        {
            Console.WriteLine("OtherMethod executing assembly: " + Assembly.GetExecutingAssembly().FullName);
            Console.WriteLine("OtherMethod called from: " + Assembly.GetCallingAssembly().FullName);
        }
    }
}
// The example produces output like the following:
// "FirstMethod called from: FirstAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
// "OtherMethod executing assembly: SecondAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
// "OtherMethod called from: FirstAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
Imports System.Reflection

Module Example
   Public Sub Main()
      ' Instantiate a target object.
      Dim int1 As Integer
      ' Set the Type instance to the target class type.
      Dim type1 As Type =int1.GetType()
      ' Instantiate an Assembly class to the assembly housing the Integer type.
      Dim sampleAssembly = Assembly.GetAssembly(int1.GetType())
      ' Display the name of the assembly that is calling the method.
      Console.WriteLine(("GetCallingAssembly = " + Assembly.GetCallingAssembly().FullName))
   End Sub
End Module
' The example displays output like the following:
'   GetCallingAssembly = Example, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

注解

如果调用 GetCallingAssembly 该方法的方法由实时 (JIT) 编译器内联扩展,或者其调用方是内联扩展的,则返回的 GetCallingAssembly 程序集可能会意外不同。 例如,请考虑以下方法和程序集:

  • 程序集M1调用A1中的方法GetCallingAssembly

  • 程序集M2调用A2中的方法M1

  • 程序集M3调用A3中的方法M2

如果未 M1 内联, GetCallingAssemblyA2返回 。 内联时 M1GetCallingAssembly 返回 A3。 同样, M2 如果未内联, GetCallingAssemblyA2返回 。 内联时 M2GetCallingAssembly 返回 A3

当作为结尾调用执行或M1作为结尾调用执行M2时,也会M2发生此M3效果。 可以通过将属性与GetCallingAssembly标志应用MethodImplAttribute来阻止 JIT 编译器内联调用MethodImplOptions.NoInlining的方法,但没有类似的机制可以阻止尾部调用。

适用于