因为它正在做更多的工作@JJS。记住你的训练并使用源,卢克。
文档为我们提供了一些线索。
Type.GetType Method (String)
- 如果某个类型在程序编译时已知的程序集中,则在 C#、Visual Basic 中的 GetType 或 C++ 中使用会更有效。
- 如果 typeName 包含命名空间但不包含程序集名称,则此方法仅按此顺序搜索调用对象的程序集和 Mscorlib.dll。
我们知道typeof(T) 是一个被编译为ldtoken 和GetTypeFromHandle 的调用,但是与GetTypeByName 相比,GetTypeFromHandle 做了什么?
让我们先解决简单的问题。
GetTypeFromHandle 定义为
[Pure]
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern Type GetTypeFromHandle(RuntimeTypeHandle handle);
让我们获得一个我们可以参考的 CLR 版本。
Shared Source Common Language Infrastructure 2.0 Release
runtimehandles.cpp
FCIMPL1(Object*, RuntimeTypeHandle::GetRuntimeType, void* th) {
CONTRACTL {
THROWS;
DISABLED(GC_TRIGGERS);
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
OBJECTREF refType = NULL;
TypeHandle typeHandle = TypeHandle::FromPtr(th);
TypeHandle* pTypeHandle = &typeHandle;
_ASSERTE(CheckPointer(pTypeHandle));
_ASSERTE(CheckPointer(pTypeHandle->AsPtr(), NULL_OK));
if (pTypeHandle->AsPtr() == NULL)
return NULL;
refType = pTypeHandle->GetManagedClassObjectIfExists();
if (refType != NULL)
return OBJECTREFToObject(refType);
HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_1(Frame::FRAME_ATTR_RETURNOBJ, refType);
refType = pTypeHandle->GetManagedClassObject();
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(refType);
}
FCIMPLEND
好的。这是合法的。我们在这里做了一个邪恶的简单调用来获取一个 OBJECTREFToObject。
没有搜索,只是通过它的方法表有效地查找一个类型。需要复习.Net internals?
好的,slow 方法呢? Type.GetType Method (String)
追踪调用堆栈,发现它调用了RuntimeTypeHandle.GetTypeByName
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, StackCrawlMarkHandle stackMark,
#if FEATURE_HOSTED_BINDER
IntPtr pPrivHostBinder,
#endif
bool loadTypeFromPartialName, ObjectHandleOnStack type);
runtimehandles.cpp
FCIMPL6(EnregisteredTypeHandle, RuntimeTypeHandle::GetTypeByName,
StringObject* classNameUNSAFE, CLR_BOOL bThrowOnError, CLR_BOOL bIgnoreCase, CLR_BOOL bReflectionOnly, StackCrawlMark* pStackMark, CLR_BOOL bLoadTypeFromPartialNameHack)
{
CONTRACTL
{
THROWS;
DISABLED(GC_TRIGGERS);
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
STRINGREF sRef = (STRINGREF) classNameUNSAFE;
TypeHandle typeHandle;
HELPER_METHOD_FRAME_BEGIN_RET_1(sRef);
{
if (!sRef)
COMPlusThrowArgumentNull(L"className",L"ArgumentNull_String");
typeHandle = TypeName::GetTypeManaged(sRef->GetBuffer(), NULL, bThrowOnError, bIgnoreCase, bReflectionOnly, /*bProhibitAsmQualifiedName =*/ FALSE, pStackMark, bLoadTypeFromPartialNameHack);
}
HELPER_METHOD_FRAME_END();
return typeHandle.AsPtr();
}
FCIMPLEND
很好,但是 TypeName::GetTypeManaged 在做什么?!
typeparse.cpp
//--------------------------------------------------------------------------------------------------------------
// This everything-but-the-kitchen-sink version is what used to be called "GetType()". It exposes all the
// funky knobs needed for implementing the specific requirements of the managed Type.GetType() apis and friends.
//--------------------------------------------------------------------------------------------------------------
/*public static */ TypeHandle TypeName::GetTypeManaged
但不止于此
typeparse.cpp
// -------------------------------------------------------------------------------------------------------------
// This is the "uber" GetType() that all public GetType() funnels through. It's main job is to figure out which
// Assembly to load the type from and then invoke GetTypeHaveAssembly.
//
// It's got a highly baroque interface partly for historical reasons and partly because it's the uber-function
// for all of the possible GetTypes.
// -------------------------------------------------------------------------------------------------------------
/* private instance */ TypeHandle TypeName::GetTypeWorker
也不止于此。
typeparse.cpp
//----------------------------------------------------------------------------------------------------------------
// This is the one that actually loads the type once we've pinned down the Assembly it's in.
//----------------------------------------------------------------------------------------------------------------
/* private instance */ TypeHandle TypeName::GetTypeHaveAssembly(Assembly* pAssembly, BOOL bThrowIfNotFound, BOOL bIgnoreCase, BOOL bRecurse)
for (COUNT_T i = 0; i < names.GetCount(); i ++)
{
LPCWSTR wname = names[i]->GetUnicode();
MAKE_UTF8PTR_FROMWIDE(name, wname);
typeName.SetName(name);
th = pAssembly->GetLoader()->LoadTypeHandleThrowing(&typeName);
}
clsload.cpp
TypeHandle ClassLoader::LoadTypeHandleThrowing(NameHandle* pName, ClassLoadLevel level, Module* pLookInThisModuleOnly/*=NULL*/)
BOOL foundSomething = FindClassModuleThrowing(pName,
// FindClassModuleThrowing 发现您要查找的类型在哪个模块中,并在必要时加载该模块。
// 基本上,它遍历程序集的所有模块,直到在模块的
// 可用类哈希表。
if (!typeHnd.IsNull()) {
typeHnd = LoadTypeDefThrowing(typeHnd.GetModule(), typeHnd.GetCl(),
// 给定一个指定 typeDef 的标记,以及一个模块
// 解释该标记,查找或加载相应的类型句柄。
typeHnd = pModule->LookupTypeDef(typeDef, level);
ceeload.h
TypeHandle LookupTypeDef(mdTypeDef token, ClassLoadLevel level = CLASS_LOAD_UNRESTOREDTYPEKEY)
这给了我们 TypeHandle。我们在 GetTypeFromHandle 的单个堆栈帧中得到了同样的东西
PTR_MethodTable pMT = PTR_MethodTable(GetFromRidMap(&m_TypeDefToMethodTableMap, RidFromToken(token)));
if (pMT == NULL || pMT->GetLoadLevel() < level)
return TypeHandle();
else
return (TypeHandle)pMT;
那么...什么是慢? FindClassModuleThrowing 中的迭代。它必须遍历名称来查找方法表...遍历数组总是比通过已知键查找内容要慢,这在GetTypeFromHandle中可用@
结案。