NETCore程序集复用技术:类型转移(TypeForwarding)
背景介绍
在netcore迁移过程中,发现原有针对netframework平台编译的dll文件,可以直接在netcore的应用(netcoreapp.31)中加载并使用。对此感到比较好奇,本文就针对此知识点进行探究和梳理。
本次演示用到的几个项目说明:- Tccc.TypeForwarding.Net451.SPI:代表针对net451平台的类库项目;
- Tccc.TypeForwarding.NetApp:代表针对net451的控制台应用项目;
- Tccc.TypeForwarding.NetCoreApp:代表针对netcore3.1的控制台应用项目;
Tccc.TypeForwarding.Net451.SPI中定义的类型Person源码如下:
public class Person
{
public string Name { get; set; }
public string Age { get; set; }
public void PrintInfo()
{
Console.WriteLine("Assembly FullName=" + typeof(string).Assembly.FullName);
Console.WriteLine("Assembly Location=" + typeof(string).Assembly.Location);
}
}
两个控制台应用的Program源码相同,均如下:
internal class Program
{
static void Main(string[] args)
{
Person p1 = new Person() { Name = "张三" };
p1.PrintInfo();
Console.ReadLine();
}
}
上述源码的目的是对比应用程序在不同平台的运行时,最常用的类型System.String所在的程序集有什么区别,并以此为突破口来探究相关技术点。
.NETFramewok平台的特征分析
现在启动Tccc.TypeForwarding.NetApp得到的结果如下:

NETCore平台的特征分析
现在来运行Tccc.TypeForwarding.NetCoreApp程序,看看输出结果有什么变化。
不过这里值得注意的时,此时Tccc.TypeForwarding.Net451.SPI的目标平台依然是net451,而且根据上面反编译我们明明看到Tccc.TypeForwarding.Net451.SPI是引用了NET Framework的著名程序集mscorlib呢?
这里我们再次反编译netcore3.1目录下的Tccc.TypeForwarding.Net451.SPI程序集,验证确实还存在mscorlib的引用;
PS:由于演示程序直接在VS中可方便查看,如果读者是以现有程序分析验证则可通过windbg的SOS扩展命令dumpdomain查看分析。


