Assembly.GetExecutingAssembly()
との違いは何typeof(program).Assembly
ですか?
4 に答える
が実行中のアセンブリにあると仮定するprogram
と、どちらも同じ値を返すはずです。ただし、スタック ウォークを行うtypeof(program).Assembly
ため、パフォーマンスが向上するはずです。Assembly.GetExecutingAssembly()
私のマシンのマイクロ ベンチマークでは、前者は約 20ns かかりましたが、後者は約 600ns で 30 倍遅くなりました。
すべてのコードを制御する場合は、常に使用する必要があると思いますtypeof(program).Assembly
。他の人がアセンブリにビルドできるソース コードを提供した場合は、Assembly.GetExecutingAssembly()
.
を呼び出すAssembly.GetExecutingAssembly()
と、呼び出しているメソッドを含むアセンブリが返されAssembly.GetExecutingAssembly()
ます。
たとえば、mscorlib.dll を呼び出すと、型が含まれているため、mscorlib.dlltypeof(string).Assembly
が返されます。一方、MyProject というプロジェクトがあり、このプロジェクトのどこかで呼び出すと、 MyProject.dllを表す Assembly インスタンスが返されます。String
Assembly.GetExecutingAssembly()
これが明確になることを願っています。
Assembly.GetExecutingAssembly():
現在実行中のコードを含むアセンブリを取得します。次の例では、現在実行中のコードのアセンブリを取得します。
Assembly SampleAssembly;
// Instantiate a target object.
Int32 Integer1 = new Int32();
Type Type1;
// Set the Type instance to the target class type.
Type1 = Integer1.GetType();
// Instantiate an Assembly class to the assembly housing the Integer type.
SampleAssembly = Assembly.GetAssembly(Integer1.GetType());
// Display the name of the assembly currently executing
Console.WriteLine("GetExecutingAssembly=" + Assembly.GetExecutingAssembly().FullName);
typeOf():
主にリフレクションで使用されます。
typeof 演算子は、型の System.Type オブジェクトを取得するために使用されます。typeof 式の形式は次のとおりです。式の実行時の型を取得するには、.NET Framework メソッド GetType を使用できます。
Example
// cs_operator_typeof.cs
// Using typeof operator
using System;
using System.Reflection;
public class MyClass
{
public int intI;
public void MyMeth()
{
}
public static void Main()
{
Type t = typeof(MyClass);
// alternatively, you could use
// MyClass t1 = new MyClass();
// Type t = t1.GetType();
MethodInfo[] x = t.GetMethods();
foreach (MethodInfo xtemp in x)
{
Console.WriteLine(xtemp.ToString());
}
Console.WriteLine();
MemberInfo[] x2 = t.GetMembers();
foreach (MemberInfo xtemp2 in x2)
{
Console.WriteLine(xtemp2.ToString());
}
}
}
出力
Int32 GetHashCode()
Boolean Equals(System.Object)
System.String ToString()
Void MyMeth()
Void Main()
System.Type GetType()
Int32 intI
Int32 GetHashCode()
Boolean Equals(System.Object)
System.String ToString()
Void MyMeth()
Void Main()
System.Type GetType()
Void .ctor()