Assembly.GetExecutingAssembly()
和typeof(program).Assembly
之间的区别是什么?
答案 0 :(得分:19)
假设program
在执行程序集中,它们都应返回相同的值。但是,typeof(program).Assembly
应该具有更好的性能,因为Assembly.GetExecutingAssembly()
执行堆栈遍历。在我的机器上的微基准测试中,前者大约需要20ns,而后者在大约600ns时慢了30倍。
如果您控制所有代码我认为您应该始终使用typeof(program).Assembly
。如果您提供了其他人可以在其程序集中构建的源代码,则需要使用Assembly.GetExecutingAssembly()
。
答案 1 :(得分:5)
调用Assembly.GetExecutingAssembly()
将返回包含调用Assembly.GetExecutingAssembly()
的方法的程序集。
调用示例typeof(string).Assembly
将返回 mscorlib.dll ,因为它包含类型String
。
另一方面,如果你有一个名为 MyProject 的项目,在这个项目的某个地方,你调用Assembly.GetExecutingAssembly()
,它将返回代表 MyProject.dll 的汇编实例
希望这澄清。
答案 2 :(得分:1)
<强> 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()
答案 3 :(得分:1)
以下代码解释了差异。
//string class is defined by .NET framework
var a = Assembly.GetAssembly(typeof(string));
//a = FullName = "mscorlib, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
由于字符串是在mscorlib程序集中定义的,因此返回其全名。因此,将在定义类型的位置返回程序集名称。如果我在我执行此代码的地方通过我的课程,
//Program is the class where this code is being executed
var aa = Assembly.GetAssembly(typeof(Program));
//aa = FullName = "Obj_2_5_Using_Reflection,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
var b = Assembly.GetExecutingAssembly();
//b = FullName = "Obj_2_5_Using_Reflection,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"