Assembly.GetExecutingAssembly()
和typeof(program).Assembly
之间的区别是什么
发布于 2013-08-14 02:51:16
假设program
在执行程序集中,它们应该返回相同的值。但是,由于Assembly.GetExecutingAssembly()
执行堆栈审核,因此typeof(program).Assembly
应该具有更好的性能。在我的机器上的一个微型基准测试中,前者大约需要20 was,而后者在大约600 was时要慢30倍。
如果你控制了所有的代码,我认为你应该始终使用typeof(program).Assembly
。如果您提供了其他人可以构建到其程序集中的源代码,则需要使用Assembly.GetExecutingAssembly()
。
发布于 2013-03-14 19:11:29
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框架方法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()
发布于 2015-11-16 21:05:32
下面的代码解释了这些差异。
//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"
因为string是在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"
https://stackoverflow.com/questions/15407340
复制相似问题