![](/img/trans.png)
[英]What's the difference between this.GetType().Assembly.GetName().Version and Assembly.GetExecutingAssembly().GetName().Version?
[英]Difference between Assembly.GetExecutingAssembly() and typeof(program).Assembly
Assembly.GetExecutingAssembly()
和typeof(program).Assembly
之间有什么区别typeof(program).Assembly
?
假设program
在执行program
集中,它们都应该返回相同的值。 但是, typeof(program).Assembly
应该有更好的性能,因为Assembly.GetExecutingAssembly()
执行堆栈遍历。 在我的机器上的微基准测试中,前者花了大约20ns,而后者在大约600ns时慢了30倍。
如果您控制所有代码,我认为您应该始终使用typeof(program).Assembly
。 如果您提供了其他人可以构建到其程序集中的源代码,则需要使用Assembly.GetExecutingAssembly()
。
调用Assembly.GetExecutingAssembly()
将返回包含调用Assembly.GetExecutingAssembly()
的方法的程序集。
调用例如typeof(string).Assembly
将返回mscorlib.dll,因为它包含String
类型。 另一方面,如果你有一个名为MyProject的项目,在这个项目的某个地方调用Assembly.GetExecutingAssembly()
,它将返回代表MyProject.dll的Assembly实例。
希望这澄清一下。
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运算符用于获取类型的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()
以下代码解释了差异。
//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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.