gpt4 book ai didi

c# - 在加载的程序集中按名称搜索类型的最快方法是什么?

转载 作者:行者123 更新时间:2023-11-30 17:03:10 27 4
gpt4 key购买 nike

我正在编写一种小型模板语言(很像 Razor),我在模板编译中必须做的一件事是根据 (1) 完全限定名称或 (2) 非限定名称解析 CLR 枚举+ 命名空间。例如:

namespace Foo.Bar {
public enum MyEnum { A, B }
}

// template:
@using Foo.Bar;
@using System;
...
@Foo.Bar.MyEnum.A // fully qualified
@MyEnum.A // unqualified, but in one of the specified namespaces

我目前的方法是扫描当前应用程序域中的所有程序集以查找枚举,它看起来类似于以下内容:

string[] namespaces = // parsed from template
string typeName = // parsed from template
string fieldName = // parsed from template

var possibleResolutions = from type in AppDomain.CurrentDomain.GetAssemblies()
.Where(a => !a.IsDynamic)
.SelectMany(a => a.GetTypes())
where type.IsEnum
from @namespace in namespaces
let fullName = @namespace + '.' + typeName
// the replace is because nested enum types (like we have in AptOne, will have a fullname of namespace.OuterClass+InnerClass)
where type.FullName.Replace('+', '.') == fullName
let field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.Static)
where field != null;

我发现这在冷启动时可能非常慢(占所有其他模板编译时间),几乎所有时间都花在 GetTypes() 上。我想知道,是否有更快的方法来进行此类查找?

请注意,我已经缓存了这些结果,所以我对那种解决方案不感兴趣。

最佳答案

您可以使用 Common Compiler Infrastructure在不进行反射的情况下扫描程序集,制作枚举列表。从他们的网站:

The CCI Metadata API allows applications to efficiently analyze or modify .NET assemblies, modules, and debugging (PDB) files. CCI Metadata supports the functionality of the .NET System.Reflection and System.Reflection.Emit APIs, but with much better performance. It also provides additional functionality that is not available in either .NET API.

然后,如果您需要实际类型,您可以通过调用 Assembly.GetType() 使用您的列表。

关于c# - 在加载的程序集中按名称搜索类型的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18898968/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com