今天在分析問題時遇到使用Type.GetType()一直返回null的情況,於是針對相關情況做了個梳理驗證。詳情如下:
測試項目的程序集介紹:
- 直接引用了Tccc.Reflection.First.SPI,沒有引用Tccc.Reflection.Second.SPI
- 內部定義了類型:School
測試代碼如下:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Reflection;
namespace Tccc.Reflection.Tests
{
/// <summary>
///
/// </summary>
public class School
{
public string Name { get; set; }
}
/// <summary>
/// Type.GetType()測試場景
/// </summary>
[TestClass]
public class TypeGetTypeTests
{
/// <summary>
///
/// </summary>
[TestMethod]
public void GetTypeTest_ClassName()
{
Type.GetType("School", true);
//失敗:參數不能僅爲類名稱
}
/// <summary>
///
/// </summary>
[TestMethod]
public void GetTypeTest_NamespaceName()
{
Type.GetType("Tccc.Reflection.Tests.School", true);
//成功,因爲School在當前程序集中定義
}
/// <summary>
///
/// </summary>
[TestMethod]
public void GetTypeTest_QualifiedName()
{
Type.GetType("Tccc.Reflection.First.SPI.UserInfoModel,Tccc.Reflection.First.SPI", true);
//成功,前提是已經添加了對Tccc.Reflection.First.SPI的引用
}
/// <summary>
///
/// </summary>
[TestMethod]
public void GetTypeTest_QualifiedName_OtherLocation()
{
Type.GetType("Tccc.Reflection.Second.SPI.UserInfoModel,Tccc.Reflection.Second.SPI", true);
//失敗,因爲未添加對Tccc.Reflection.Second.SPI的引用
}
[TestMethod]
public void GetTypeTest_QualifiedName_OtherLocation_Load()
{
var loadedAssembly = Assembly.LoadFrom(@"C:\Users\chenz\Downloads\Second.SPI\Tccc.Reflection.Second.SPI.dll");
Assert.IsNotNull(loadedAssembly);
Type.GetType("Tccc.Reflection.Second.SPI.UserInfoModel,Tccc.Reflection.Second.SPI", true);
//net451失敗,
//net3.1成功,
}
}
}
知識點:
- 當目標類型在當前程序集或者系統程序集(mscorlib.dll/System.Private.CoreLib.dll)中,則入參只需要類型命名空間名稱即可。
- 當目標類型在其它程序中,則入參需要程序集限定名,即QualifiedName
- 在NETFramework和netcore平臺,對於程序集所在位置的要求不同。
當Type.GetType()返回null時依次檢查:
- 1、參數是否包含類型的命名空間
- 2、目標類型定義是否在當前程序集中
- 3、目標類型在外部程序集時,要用帶程序集的限定名稱,即QualifiedName
- 4、當程序爲netframework應用:要求目標類型所在的程序集在CLR的合法搜索路徑中。即便Assembly.LoadFrom()也無效。
- 5、當程序爲netcore應用:要求目標類型所在的程序集在CLR的合法搜索路徑中或者通過Assembly.LoadFrom()單獨加載。
4、5的驗證截圖如下: