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();
}
}
}
在调试模式下运行(按F5键)时会打印'True',但在没有调试器的情况下启动(按Ctrl-F5键)时会打印'False'。其他类也表现出类似的行为(System.Text.RegularExpressions.Regex
),而其他类则在两种情况下都存在(System.IO.File
)。
我可能忽略了一些显而易见的东西 - 这是为什么?
(在Visual Studio 2005和2008中均发生相同的情况)。
更新
找到的程序集列表:
调试模式:
mscorlib
TestReflection
System
Microsoft.VisualStudio.HostingProcess.Utilities
System.Windows.Forms
运行模式:
mscorlib
TestReflection
如答案所示,在运行模式下,系统装配件丢失(未加载)。我的问题是我以为 GetAssemblies() 也返回了未加载的程序集。
虽然这解释了 System.Diagnostics.Process 的行为,但为什么我的代码在运行和调试模式下都能找到 System.IO.File 呢?
谢谢!
更新2
我已经更改了代码,通过循环遍历已加载的程序集和当前程序集,收集这些程序集引用的程序集的列表。如果在迭代加载的程序集后找不到我要查找的类型,则开始加载并检查引用的程序集。
似乎即使我在项目中对 System.dll 进行了引用(我正在查看 Visual Studio 中“System”引用的属性),我的可执行文件只引用 mscorlib.dll(根据 Reflector 中的显示)。
如何添加对 System.dll 的“真实”引用?放置一个虚拟行
new System.Diagnostics.ProcessStartInfo();
在
Main
的开头就能解决这个问题(在检查可执行文件时,Reflector显示了对mscorlib.dll
和System.dll
的引用),但这是一种hack方法。再次感谢!
DateTime.Now
,我希望能够查找DateTime类,然后在DateTime中查找名为“Now”的公共方法/属性/字段。 - Miron Brezuleanu