英語で読む

次の方法で共有


Assembly.GetCallingAssembly メソッド

定義

現在実行中のメソッドを呼び出したメソッドの Assembly を返します。

C#
public static System.Reflection.Assembly GetCallingAssembly();

戻り値

現在実行中のメソッドを呼び出したメソッドの Assembly オブジェクト。

次の例では、現在のメソッドの呼び出し元アセンブリを取得します。

C#
// 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"

注釈

メソッドを呼び出す GetCallingAssembly メソッドが Just-In-Time (JIT) コンパイラによってインライン展開されている場合、またはその呼び出し元がインラインで展開されている場合は、 によって GetCallingAssembly 返されるアセンブリが予期せず異なる場合があります。 たとえば、次のメソッドとアセンブリについて考えてみましょう。

  • アセンブリの メソッドM1は を呼び出しますGetCallingAssemblyA1

  • アセンブリの メソッドM2は を呼び出しますM1A2

  • アセンブリの メソッドM3は を呼び出しますM2A3

がインライン化されていない場合 M1GetCallingAssembly は を返します A2。 がインライン化されている場合 M1GetCallingAssembly は を返します A3。 同様に、 がインライン化されていない場合 M2 は を GetCallingAssembly 返します A2。 がインライン化されている場合 M2GetCallingAssembly は を返します A3

この効果は、 から末尾の呼び出しとして実行されるM1場合、または からM2M3末尾呼び出しとして実行される場合M2にも発生します。 JIT コンパイラが を呼び出すメソッドのインライン化を防ぐには、 フラグを使用して 属性MethodImplOptions.NoInliningMethodImplAttribute適用しますが、末尾の呼び出GetCallingAssemblyしを防ぐための同様のメカニズムはありません。

適用対象

製品 バージョン
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1