以下代码(打包在'Console Application'Visual Studio项目中):
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace TestReflection
{
class Program
{
static void Main(string[] args)
{
bool found = false;
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.GetType("System.Diagnostics.Process") != null)
{
found = true;
break;
}
}
Console.WriteLine(found);
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在调试模式(F5)下运行时打印'True',但在没有调试器的情况下启动它时为'False'(Ctrl-F5).其他类显示类似的行为(System.Text.RegularExpressions.Regex),其他类在两种情况下都可以找到(System.IO.File).
我可能错过了一些明显的东西 - 为什么会这样?
(同样的事情发生在Visual Studio 2005和2008中).
找到的组件列表:
调试模式:
mscorlib
TestReflection
System
Microsoft.VisualStudio.HostingProcess.Utilities
System.Windows.Forms
Run Code Online (Sandbox Code Playgroud)
运行模式:
mscorlib
TestReflection
Run Code Online (Sandbox Code Playgroud)
正如答案所暗示的那样,在运行模式下,系统组件丢失(未加载).我的问题是我假设GetAssemblies()也返回未加载的程序集.
虽然这解释了行为System.Diagnostics.Process,为什么我的代码System.IO.File在运行和调试模式下都能找到?
谢谢!
我已经将代码更改为循环加载的程序集和当前程序集,收集这些程序集引用的程序集列表.如果迭代加载的程序集后我找不到我正在寻找的类型,我开始加载并检查引用的程序集.
看来即使我System.dll在我的项目中有一个引用(我正在查看Visual Studio中'System'引用的属性),我的可执行文件只引用mscorlib.dll(根据Reflector).
如何添加"真实"引用System.dll?放置虚线
new System.Diagnostics.ProcessStartInfo();
Run Code Online (Sandbox Code Playgroud)
Main诀窍的开始(事情按预期工作,Reflector显示两者的参考mscorlib.dll和System.dll检查可执行文件时),但它是一个黑客.
再次感谢!
Pet*_*old 11
AppDomain.GetAssemblies不会返回您引用的所有程序集,而是返回当前加载到appdomain中的所有程序集.
显然,您的应用程序不直接使用Diagnostics.Process类,因此在调试器外部运行时不会加载.
那么为什么我们找到System.IO.File而不是System.Diagnostics.Process?原因是这两个类虽然位于同一个顶级命名空间System中,但实际上存在于两个不同的程序集中.如果在Visual Studio对象浏览器中查找这两个类,则很容易看到这一点.File类恰好存在于mscorlib dll中,而Process类存在于System dll中.
因为没有mscorlib,所以没有.Net应用程序可以在没有加载程序集的情况下运行,因为你没有加载System.dll,因为你没有引用该dll中的任何类型.