C#如何获取非系统程序集
我需要实例化一个仅在程序程序集或 mscorlib 中定义的对象,而不是在任何其他系统程序集中定义的对象。目前我正在这样做:
Type type;
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
string fullName = name + "," + assembly.FullName;
type = Type.GetType(fullName);
if (type != null) break;
}
if (type != null)
object obj = Activator.CreateInstance(type);
有没有办法优化这个循环以跳过系统程序集(但不是 mscorlib)?我需要多次调用这个。
谢谢!
I need to instantiate an object that is defined only in the program assemblies or mscorlib, and not in any other system assemblies. Currently I'm doing this:
Type type;
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
string fullName = name + "," + assembly.FullName;
type = Type.GetType(fullName);
if (type != null) break;
}
if (type != null)
object obj = Activator.CreateInstance(type);
Is there a way to optimize this loop to skip the system assemblies (but not mscorlib)? I need to call this multiple times.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以尝试这样的事情:
一旦你有了“loadedAssemblies”,你就可以用它来做你需要做的事情。
如果您多次调用此函数,请将加载的程序集存储在一个变量中,这样您就不会每次都查询,而只是迭代列表。
You can try something like this:
Once you have "loadedAssemblies" you can do what you need to do with this.
If you're calling this multiple times, then store the loaded assemblies in a variable so you don't query each time but rather just iterate over the list.
您可以调用Load()。来自评论:
http://msdn.microsoft.com/en-us/library /36az8x58.aspx
然而,在幕后,我不确定这是否比你的 O(n) 循环更快(甚至任何不同)。您可能想对它们进行测试。如果您需要为多个程序集运行此循环,那么我建议运行一次循环并找到您需要的所有程序集。如果您对同一个程序集多次运行此循环,那么我建议您使用单例类型模式,您可以在其中获取一次引用,而无需再查看。
You can call Load(). From the remarks:
http://msdn.microsoft.com/en-us/library/36az8x58.aspx
However, under the hood, I'm not sure if this is faster than your O(n) loop (or even any different). You might want to test them both out. If you need to run this loop for multiple assemblies then I suggest running the loop once and finding all the assemblies you need in that go. If you are running this loop multiple times for a same assembly then I suggest a singleton type pattern where you can get the reference once and never look again.
如果您知道所有程序集,您可以将它们收集起来。您还可以加载 Mscorlib.dll,而无需迭代每个程序集。本质上,我建议使用白名单而不是黑名单。
汇编 assembly = Assembly.Load("Mscorlib.dll");
http://ondotnet.com/pub/a/dotnet/excerpt/prog_csharp_ch18/index.html?page=5
If you know all of your program assemblies you could just make a collection of those. You can also load Mscorlib.dll without having to iterate through every assembly. In essence I'm proposing whitelisting as opposed to blacklisting.
Assembly assembly = Assembly.Load("Mscorlib.dll");
http://ondotnet.com/pub/a/dotnet/excerpt/prog_csharp_ch18/index.html?page=5